C#.net downloading files from FTP to local /*first read the FTP login information from the configuration file*/
stringTempfolderpath = system.configuration.configurationmanager.appsettings["Tempfolderpath"]. ToString ();
stringFtpUserName = system.configuration.configurationmanager.appsettings["FtpUserName"]. ToString ();
stringFTPPassword = system.configuration.configurationmanager.appsettings["FTPPassword"]. ToString ();
stringLocalfileexistsoperation = system.configuration.configurationmanager.appsettings["localfileexistsoperation"]. ToString ();
Uri uri =NewUri (Ftppath);
stringFileName = Path.GetFullPath (tempfolderpath) + Path.DirectorySeparatorChar.ToString () + Path.getfilename (URI. LocalPath);
//Create a file stream
FileStream fs =NULL;
Stream Responsestream =NULL;
Try
{
//Create a FtpWebRequest object to contact the FTP server
FtpWebRequest request = (ftpwebrequest) webrequest.create (URI);
//the way to set the request is to download the ftp file
Request. Method = WebRequestMethods.Ftp.DownloadFile;
//connect to log on to the FTP server
Request. Credentials =NewNetworkCredential (FtpUserName, FTPPassword);
//gets a request response object
FtpWebResponse response = (ftpwebresponse) request. GetResponse ();
//gets the requested response stream
Responsestream = Response. GetResponseStream ();
//determine if the local file exists, and if so, open and rewrite the local file
if(File.exists (FileName))
{
if(Localfileexistsoperation = ="Write")
{
FS = File.Open (FileName, FileMode.Open, FileAccess.ReadWrite);
}
}
//determine if the local file exists and if it does not, create a local file
Else
{
FS = File.create (FileName);
}
if(FS! =NULL)
{
intBuffer_count =65536;
byte[] buffer =Newbyte[Buffer_count];
intSize =0;
while(size = responsestream.read (buffer,0, Buffer_count)) >0)
{
Fs. Write (Buffer,0, size);
}
Fs. Flush ();
Fs. Close ();
Responsestream.close ();
}
}
finally
{
if(FS! =NULL)
Fs. Close ();
if(Responsestream! =NULL)
Responsestream.close ();
}
If you encounter a server-side download path that contains Chinese characters, add it under the <system.web> node in the configuration file Web. config:
<globalization requestencoding="GB2312"responseencoding="GB2312"Uiculture="ZH-CN"Culture="ZH-CN"fileencoding="GB2312"The/> can be solved.