Tips, tricks, and frustrations from my years of building ASP.NET websites.

Sunday, April 6, 2008

Anonymous FTP in ASP.NET the easy way

There is an easy way to do an anonymous FTP in ASP.NET. The trick is to use the WebClient class to perform the operation.

The function below will perform the FTP and return the StreamReader to read the newly downloaded file:


using System;
using System.Security.Permissions;
using System.Net;
using System.IO;


System.IO.StreamReader AnonFTP(string theFileToDownload, string theLocalFile)
{
try
{
WebClient request = new WebClient();

// FTP site uses anonymous logon.
request.Credentials =
new NetworkCredential("anonymous","YourEmail@YourHost.com");

request.DownloadFile(theFileToDownload,theLocalFile);
return new System.IO.StreamReader(theLocalFile);
}
catch
{
return null;
}
}



Sample Invocation:

AnonFTP("ftp://x.com/dat.txt", "C:\\test.txt");

No comments:

About Me

I'm currently employed as a Senior Systems Programmer/Analyst and sometimes Project Manager at Texas Instruments Inc. in Plano TX.