Monday, August 16, 2010

C# FAQs Series: How Use FTP Using C#


àIn C# FAQs Series: We discuss most frequent questions asked on C# forums.
As a C# developer you may often have to use FTP. Following is simple program which will demonstrate how to FTP using C#.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Geting the object used to communicate with the server.
FtpWebRequest FWRrequest = (FtpWebRequest)WebRequest.Create( "ftp://www.mrmubi.com/mytest.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// Set network credentials.
FWRrequest.Credentials = new NetworkCredential ("user","password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("myfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
FWRrequest.ContentLength = fileContents.Length;
Stream requestStream = FWRrequest.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("File upload complete , status {0}", response.StatusDescription);
response.Close();
}
}
}
}
How to download file using FTP in C#...
public static bool DisplayFileFromServer(Uri serverUri)
{
    // The serverUri parameter should start with the ftp:// scheme.
    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Geting the object used to communicate with the server.
    WebClient WCrequest = new WebClient();
 
    // Credentials
    WCrequest.Credentials = new NetworkCredential ("user","password");
    try 
    {
        byte [] newFileData = WCrequest.DownloadData (serverUri.ToString());
        string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
        Console.WriteLine(fileString);
    }
    catch (WebException e)
    {
        Console.WriteLine(e.ToString());
    }
    return true;
}
How to delete file using FTP in C#...
public static bool DeleteFileOnServer(Uri serverUri)
{
    // The serverUri parameter should use the ftp:// scheme.
    // It contains the name of the server file that is to be deleted.
    // Example: ftp://contoso.com/someFile.txt.
    // 
 
    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Get the object used to communicate with the server.
    FtpWebRequest FWRrequest = (FtpWebRequest)WebRequest.Create(serverUri);
    FWRrequest.Method = WebRequestMethods.Ftp.DeleteFile;
 
    FtpWebResponse FWRresponse = (FtpWebResponse) FWRrequest.GetResponse();
    Console.WriteLine("File delete status: {0}",FWRresponse.StatusDescription);  
    FWRresponse.Close();
    return true;
}
You see how easy is it to play with your FTP account in C#.

No comments:

Post a Comment