Ftp operations

You can use a list of Ftp operation defined as string constants in WebRequestMethods.Ftp:

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);



    }

}

Rename command

You must populate the request's RenameTo property with the new filename (without a directory prefix).

For example, to rename a file in the incoming directory from tempfile.txt to deleteme.txt:


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.Rename;
        req.RenameTo = "deleteme.txt";

        req.GetResponse().Close();  // Perform the rename
    }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.