[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Log into FTP and delete files in the folder

Posted on 2010-01-03
29
Medium Priority
?
1,183 Views
Last Modified: 2013-12-02
i try to run a console app which will delete the conditional files in folder :
ftp://ftp1.abcde.com/123/abce/123/ab/

it comes with login credential.

sample file name to be deleted :
bpcs_20100104_13c_08_00_08_aus_ph2.txt


string[] files = Directory.GetFiles(@"C:\\testfolder");

            foreach (string file in files)
            {
                if (file.Length == 53 && file.Substring(17, 1) == "c")
                {
                    File.Delete(file);
                }
            }

Open in new window

0
Comment
Question by:doramail05
  • 13
  • 13
  • 3
29 Comments
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26168449
Hi there;

well, I thnik the original question was:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_25016634.html

which if you go back to the question and go back at end of the thread with the ID: 26168259, you can see the point:

When the address is as below:
ftp://ftp1.abcde.com/123/abce/123/ab/bpcs_20100104_13c_08_00_08_aus_ph2.txt

The code should be as below. Please inform me, if it won't work, I will help you gladly and could you go back to original question in the link above, and inform us whether the accepted solution is true, since when I run for it, it deletes both files in that question.

Best regards.
            foreach (string file in files) 
            { 
 
                //For below: 
 
                //bpcs_20100104_12c_08_00_08_aul_ph2 not fits. 
                //bpcs_20100104_13_07_00_07_aus_ph2 not fits. 
 //31
                //I:\\\\testfolder\\WirelessDiagLog.csv fits fits. 
                //I:\\\\testfolder\\bpcs_20100104_12c_08_00_08_aul_ph2 fits. 
 //For FTP //36
 
                if (file.ToString().Substring(36,1).Equals("c")) 
                {                                     
                    textBox1.Text = "\nDeleted file: "; 
                    textBox1.AppendText("***" + file.ToString() + "***"); 
                    File.Delete(file); 
                } 
                else 
                { 
                    textBox1.Text = "\nPreserved file: "; 
                    textBox1.AppendText("***" + file.ToString() + "***"); 
                } 
            }

Open in new window

0
 
LVL 1

Author Comment

by:doramail05
ID: 26168473
there's no need any additional code for accessing ftp with username and password? supposingly it has to be some coding which deals with login to ftp, and pointing to the directory of the ftp folder .etc.
0
 
LVL 1

Author Comment

by:doramail05
ID: 26168486
im not sure at this moment
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 9

Expert Comment

by:magicdlf
ID: 26168544
The System.IO will not work for FTP site. You may need a 3rd-party lib to help you achieve this.
Take a look at those::
http://ftplib.codeplex.com/
http://www.codeproject.com/KB/IP/ftplib.aspx

0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26168575
Hi there;

You can use the following code for conditional stuff that returns the relative path name of the file

Best regards.
        public void delete()
        {
            string[] files = Directory.GetFiles("I:/testfolder");
         
            FileInfo fi = null;

            for (int i = 0; i < files.Length; i++)
            {
                fi = new FileInfo(files[i]);
                
                string path = fi.ToString();
                int position = 0;
                position = path.LastIndexOf('\\');

                
                string first = path.Substring(0, position + 1);
                string real = path.Substring(position + 1);
                //DEBUG:
                //textBox1.AppendText("real: " + real.Substring(17, 1) + "\n");
                if (real.Substring(16,1).Equals("c"))
                {
                    textBox1.AppendText("\nDeleted file: ");
                    textBox1.AppendText("\n***" + path + "***");
                    fi.Delete();
                }

            }

    
        }

Open in new window

0
 
LVL 12

Accepted Solution

by:
jazzIIIlove earned 2000 total points
ID: 26168590
Please go back to your the question, http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_25016634.html

and respond us whether the accepted answer is really true or not since I failed to run it and doubts regarding it.

Below code snippet is what you need:
That was an old program I had written that decrypts a file in ftp.
You must work on it with the very above code of mine.

Best regards.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace FTPARP
{
    class Program
    {

        static void Main(string[] args)
        {
            FtpWebRequest request = FtpWebRequest.Create("ftp://someaddress/somefile.txt") as FtpWebRequest;
            //request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential("yourname", "yourpass");
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = true;
            FtpWebResponse response = request.GetResponse() as FtpWebResponse;
            Stream responseStream = response.GetResponseStream();
            //... FTP commands
            List<string> files = new List<string>();
            StreamReader reader = new StreamReader(responseStream);

            /*
            while (!reader.EndOfStream)
            {            
            files.Add(reader.ReadLine());
            }
            
                Console.WriteLine(files.ElementAt(0));
            */

            // Stream responseStream = response.GetResponseStream();

            MemoryStream memStream = new MemoryStream();
            int Size = 1024;
            byte[] buffer = new byte[Size];
            int bytesRead = responseStream.Read(buffer, 0, buffer.Length);
            while (bytesRead != 0) //while(true)
            {
                //Try to read the data
                //bytesRead = reader.Read(buffer, 0, buffer.Length);
                bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                //Write the downloaded data
                memStream.Write(buffer, 0, bytesRead);
            }
            byte[] downloadedData = new byte[0];
            //Convert the downloaded stream to a byte array
            downloadedData = memStream.ToArray();

            //Clean up
            reader.Close();
            memStream.Close();

            //for (int i = 0; i < downloadedData.Length; i++)
            //Console.Write("aa" + (char)downloadedData[i]);

            System.Text.Encoding enc = System.Text.Encoding.ASCII;

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
            info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
           
            process.StartInfo = info;
            process.Start();

            //Console.Write(enc.GetString(downloadedData).ToString());
            //StreamWriter sw = new StreamWriter("c:\\ultimatearp.txt");

            // write a line of text to the file
            //sw.Write(enc.GetString(downloadedData).ToString());

            responseStream.Close();
            response.Close(); //Closes the connection to the server
            //sw.Close();
        }
    }
}

Open in new window

0
 
LVL 1

Author Comment

by:doramail05
ID: 26168598
i was more worry about the code for ftp access. Becoz The 'I' drive could not be the correct drive rite?
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26168602
>>The System.IO will not work for FTP site.
I don't think so, please examine above code imports.
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26168610
well, your worry is my worry but you must correct the other question, if there is something wrong with it, other than that, I wouldn't be helping you sadly.

Best regards.
0
 
LVL 1

Author Comment

by:doramail05
ID: 26168637
..!
what i put is that the code for deleting the files between

process.StartInfo = info;
            process.Start();

            *here* ?

            responseStream.Close();
            response.Close();

how about the drive folder "I", it does not look like a correct folder name in the ftp
process.StartInfo = info;
process.Start();

            //Console.Write(enc.GetString(downloadedData).ToString()); 
            //StreamWriter sw = new StreamWriter("c:\\ultimatearp.txt"); 

            // write a line of text to the file 
            //sw.Write(enc.GetString(downloadedData).ToString()); 

            responseStream.Close();
            response.Close();

Open in new window

0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26168645
*here* ?
starts an arp command in local machine, so as I said, this is not your full code above, but It definitely helps to connect FTP server and you must combine the other code I have given.

If you put your ftp address to the code in ID: 26168575, there won't be any problem since I deliminite it with '/' and as I said in the other question, you need to work on relative paths, not full paths.
0
 
LVL 1

Author Comment

by:doramail05
ID: 26168664
something like the code below :  ?
process.StartInfo = info; 
process.Start(); 
 
            delete();  
 
            responseStream.Close(); 
            response.Close();


public void delete() 
        { 
            string[] files = Directory.GetFiles("I:/testfolder"); 
          
            FileInfo fi = null; 
 
            for (int i = 0; i < files.Length; i++) 
            { 
                fi = new FileInfo(files[i]); 
                 
                string path = fi.ToString(); 
                int position = 0; 
                position = path.LastIndexOf('\\'); 
 
                 
                string first = path.Substring(0, position + 1); 
                string real = path.Substring(position + 1); 
                //DEBUG: 
                //textBox1.AppendText("real: " + real.Substring(17, 1) + "\n"); 
                if (real.Substring(16,1).Equals("c")) 
                { 
                    textBox1.AppendText("\nDeleted file: "); 
                    textBox1.AppendText("\n***" + path + "***"); 
                    fi.Delete(); 
                } 
 
            } 
 
     
        }

Open in new window

0
 
LVL 9

Expert Comment

by:magicdlf
ID: 26168674
jazzIIIlove, are you going to map the FTP site as I: drive in your solution?
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26168764
Of course not, in that code, I was referring how to extract the file regarding relative paths.

As, you see in the attachment, I am using Net libraries and reach the remote stuff and the output the hierarchy of an FTP server.

>>>>The System.IO will not work for FTP site.
>>I don't think so, please examine above code imports.
Simply by streaming, I am reaching the file content etc. that's reason why I wrote above comment.
As you examine the code imports, I am using Net library for the stuff.

Best regards.
remoteftp.jpg
0
 
LVL 9

Expert Comment

by:magicdlf
ID: 26168773
Sounds good to me. Well done. : )
0
 
LVL 1

Author Comment

by:doramail05
ID: 26168779
nice screenshot,

but the line below :
string[] files = Directory.GetFiles("I:/testfolder");  

should it be Directory.GetFiles("ftp://ftp1.abcde.com/123/abcd/123/ab/"); ?
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26168784
So, after all, we don't need a 3rd party, you can have your party here...:)
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26168790
>>should it be Directory.GetFiles("ftp://ftp1.abcde.com/123/abcd/123/ab/"); ?
no, you cannot get the hierarchy with that since it's not supported as I say above, you must adapt both code segments.

I have given Directory.GetFiles referring to your other question which semantically false, that you must extract the filename as a relative path from the absolute path.

Best regards.
0
 
LVL 1

Author Comment

by:doramail05
ID: 26169076
string[] files = Directory.GetFiles("I:/testfolder");  

that is the one you have suggested,
but what it suppose to be when running live on ftp ?
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26169117
Well, did you check the above comment by luck?
string[] files = Directory.GetFiles("I:/testfolder");  

That line of code was for semantics, I have given that code segment, to help you to extract the file name, and you cannot reach an FTP site via Directory class as you may have already tested.

Best regards.
0
 
LVL 1

Author Comment

by:doramail05
ID: 26169195
FtpWebRequest request = FtpWebRequest.Create("ftp://someaddress/somefile.txt") as FtpWebRequest;

issit this one? the somefile.txt is pointing to only a file right? but i try to only reach the ftp destination, and navigate with methods that are going to browse thru folders.
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26169465
Needless to say, you are going to remove that somefile.txt and retrieve the file hierarchy with FTP classes then you are going to process the file names etc.
0
 
LVL 1

Author Comment

by:doramail05
ID: 26169748
something like that?.. using the files in list collection and loop thru, then delete based on condition?
List<string> files = new List<string>();

// then loop thru the file for condition checking and delete?

FileInfo fi = null; 
 
            for (int i = 0; i < files.Length; i++) 
            { 
                fi = new FileInfo(files[i]); 
                 
                string path = fi.ToString(); 
                int position = 0; 
                position = path.LastIndexOf('\\'); 
 
                 
                string first = path.Substring(0, position + 1); 
                string real = path.Substring(position + 1); 
                //DEBUG: 
                //textBox1.AppendText("real: " + real.Substring(17, 1) + "\n"); 
                if (real.Substring(16,1).Equals("c")) 
                { 
                    textBox1.AppendText("\nDeleted file: "); 
                    textBox1.AppendText("\n***" + path + "***"); 
                    fi.Delete(); 
                } 
 
            }

Open in new window

0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26182447
Well...Nope...

You have to use webrequest and response to perform the operations:
get the hierarchy, thenyou can store it some kind of collection, your list, then perform the check for 'c' character as in the other question or in my previous comments, then you again must perform FTP response with streaming and delete the files. The idea is just as this.

Best regards.
0
 
LVL 12

Expert Comment

by:jazzIIIlove
ID: 26199865
ok, what is your progress?
0
 
LVL 1

Author Comment

by:doramail05
ID: 26356156
i got this error : The requested URI is invalid for this FTP command.

public static string ftpstring = "ftp://ftp1.lfdis.com/";

        public Form1()
        {
            InitializeComponent();
        }
               
        private void Form1_Load(object sender, EventArgs e)
        {
            FtpWebRequest request = FtpWebRequest.Create(ftpstring + "wms/us//in/") as FtpWebRequest;
            //request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            ...
             FtpWebResponse response = request.GetResponse() as FtpWebResponse;     <---- error


0
 
LVL 1

Author Comment

by:doramail05
ID: 26356382
for my understanding,

1) FtpWebRequest
2) Collect file into List
3) Perform Delete (with fi.Delete();  )
4) close responseStream

Im trying to understand the reason of using memstream , read the data, write the downloaded data, Convert the downloaded stream to a byte array, and the ProcessCaller.
:?
0
 
LVL 1

Author Comment

by:doramail05
ID: 26356469
That's a slight change request when the file name will be used to check with the Oracle database, and if found out that the SAR_STATUS is 'COMPLETED', then the file shall be removed from ftp,

pls clarify if the code is incorrect.
while (!reader.EndOfStream) 
            {             
                files.Add(reader.ReadLine());

                using (OracleConnection oraconn = new OracleConnection(connstring))
                {

                    FileInfo fi = null;

                    for (int i = 0; i < files.Count; i++)
                    {
                        fi = new FileInfo(files[i]);  
                        string strSQL = "select * from utl_source_arrivals where sar_file_name like '" + files[i].ToString()  + "'";

                        DataSet ds = new DataSet();
                        OracleDataAdapter adapter = new OracleDataAdapter(strSQL, connstring);
                        adapter.Fill(ds);

                        if (ds.Tables[0].Rows[0]["SAR_STATUS"] == "COMPLETED")
                        {
                            fi.Delete();
                        }

                    }
                }

            } 

Open in new window

0
 
LVL 1

Author Closing Comment

by:doramail05
ID: 31680198
almost
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Introduction People like FTP.  It's a solid, stable, robust protocol for quickly transferring files between two hosts using TCP/IP.  In most cases it's much faster than SMB or CIFS, and certainly much easier to set up between organizations.  This…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question