string TempFolderPath = System.Configuration.ConfigurationManager.AppSettings["TempFolderPath"].ToString();
string FtpUserName = System.Configuration.ConfigurationManager.AppSettings["FtpUserName"].ToString();
string FtpPassWord = System.Configuration.ConfigurationManager.AppSettings["FtpPassWord"].ToString();
string LocalFileExistsOperation = System.Configuration.ConfigurationManager.AppSettings["LocalFileExistsOperation"].ToString();
Uri uri = new Uri(FtpPath);
string FileName = Path.GetFullPath(TempFolderPath) + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(uri.LocalPath);
//創建一個文件流
FileStream fs = null;
Stream responseStream = null;
try
{
//創建一個與FTP服務器聯系的FtpWebRequest對象
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
//設置請求的方法是FTP文件下載
request.Method = WebRequestMethods.Ftp.DownloadFile;
//連接登錄FTP服務器
request.Credentials = new NetworkCredential(FtpUserName, FtpPassWord);
//獲取一個請求響應對象
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//獲取請求的響應流
responseStream = response.GetResponseStream();
//判斷本地文件是否存在,如果存在,則打開和重寫本地文件
if (File.Exists(FileName))
{
if (LocalFileExistsOperation == "write")
{
fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite);
}
}
//判斷本地文件是否存在,如果不存在,則創建本地文件
else
{
fs = File.Create(FileName);
}
if (fs != null)
{
int buffer_count = 65536;
byte[] buffer = new byte[buffer_count];
int size = 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();
}
如果遇到服務器端下載路徑包含漢字的話,就在配置文件web.config中的<system.web>節點下添加:
<globalization requestEncoding="GB2312" responseEncoding="GB2312" uiCulture="zh-CN" culture="zh-CN" fileEncoding="GB2312" /> 就可以解決了。