Mega Code Archive

 
Categories / C# Book / 08 Net
 

0598 Ftp operations

You can use a list of Ftp operation defined as string constants in WebRequestMethods.Ftp: AppendFile DeleteFile DownloadFile GetDateTimestamp GetFileSize ListDirectory ListDirectoryDetails MakeDirectory PrintWorkingDirectory RemoveDirectory Rename UploadFile UploadFileWithUniqueName To run one of these commands, you assign its string constant to the web request's Method property, and then call GetResponse(). Here's how to get a directory listing: using System; using System.Net; using System.Threading; using System.IO; using System.Text; class ThreadTest { static void Main() { var req = (FtpWebRequest)WebRequest.Create("ftp://ftp.yourFtp.com"); req.Proxy = null; req.Credentials = new NetworkCredential("nutshell", "yourValue"); req.Method = WebRequestMethods.Ftp.ListDirectory; using (WebResponse resp = req.GetResponse()) using (StreamReader reader = new StreamReader(resp.GetResponseStream())) Console.WriteLine(reader.ReadToEnd()); } } To get the result of the GetFileSize command, just query the response's ContentLength property: using System; using System.Net; using System.Threading; using System.IO; using System.Text; class ThreadTest { static void Main() { var req = (FtpWebRequest)WebRequest.Create("ftp://ftp.albahari.com/tempfile.txt"); req.Proxy = null; req.Credentials = new NetworkCredential("nutshell", "yourValue"); req.Method = WebRequestMethods.Ftp.GetFileSize; using (WebResponse resp = req.GetResponse()) Console.WriteLine(resp.ContentLength); // 6 } } The GetDateTimestamp command: using System; using System.Net; using System.Threading; using System.IO; using System.Text; class ThreadTest { static void Main() { var req = (FtpWebRequest)WebRequest.Create("ftp://ftp.yourFtp.com/tempfile.txt"); req.Proxy = null; req.Credentials = new NetworkCredential("nutshell", "yourValue"); req.Method = WebRequestMethods.Ftp.GetDateTimestamp; using (var resp = (FtpWebResponse)req.GetResponse()) Console.WriteLine(resp.LastModified); } }