Understanding the basic of FtpWebRequest programming model on .Net frameworks

A long standing complain from user of .Net frameworks was that it doesn't have support for popular ftp protocol. This concern is going to addressed in .Net frameworks 2.0. Recently released Whidbey Beta-1 contains FtpWebRequest, FtpWebResponse classes to support FTP protocol.

WebRequest/ WebResponse Model

.Net frameworks support for FTP protocolo is implemented on top of WebRequest/WebResponse programming model, which was part of previous versions of  .net frameworks. Here are some key differences, later part of the document also provide some code samples to address these differences

a) Uri Based programming model 

Request/response programming model request is based on full Uri, so FtpWebRequest user would use Uri  as compare to traditional filename and directory name based programming. Your target Uri could indicate directory name or filename depending on the ftp method



AppendFile, DownloadFile ,DeleteFile, GetDateTimeStamp, UploadFile

Uri is file name like ftp://myftpserver/dir1/dir2/test.gif

ListDirectory, ListDirectoryDetails, RemoveDirectory, UploadFileWithUniqueName


Uri indicates directory name like ftp://myftpserver/dir1/dir2

b) All Ftp Connection Management is hidden to users and internal for users of FtpWebRequest and FtpWebResponse, each FtpWebRequest object is independent Ftp request, User should need write code for only Ftp operation he is doing, example to download file

FtpWebRequest request = WebRequest.Create( "ftp://myftpserver/dir1/dir2/test.htmf");

request.Credentials = new NetworkCredential("username","pass");

WebResponse response = request.GetResponse();

Stream dataStream = response.GetResponseStream();

// Now you can read stream containing the file data

c) Upoloading and downloading the data follows the standard Stream based pattern for .Net frameworks and allow user to use other stream based classes like StreamReader and StreamWriter on top of it as shown below

StreamReader sr = new StreamReader(responseStream, Encoding.ASCII);
string ss = sr.ReadToEnd(); 

d) Some advanced feature for Ftp Requests like Ftp pver SSL and Ftp requests through http proxy tunneling are very simple to program,

To go via HttpProxy you can just set Proxy property on WebRequest Object like below

request.Proxy = new WebProxy("https://myproxy"); // go through http proxy

request.EnableSSL = true; // Your web request would use SSL channel to talk to ftp server

Note on using Http Proxy on FTPWebRequest: Http proxy is only supported for limited number of ftp methods (mainly to download file only), so if you have IE settings for proxy on your machine you need to explicitly set FtpWebRequest to not use proxy like below

request.Proxy = GlobalProxySelection.GetEmptyWebProxy();

Keep looking at this weblog for more net class library 2.0 features


This posting is provided "AS IS" with no warranties, and confers no rights