asp教程.net c#利用FtpWebRequest上傳下載檔案執行個體
根據uri建立FtpWebRequest對象
FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(strUri));
// ftp使用者名稱和密碼
ftpReq.Credentials = new NetworkCredential("使用者名稱", "密碼");
// 指定執行什麼命令
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
//成功執行一個命令後串連被關閉
ftpReq.KeepAlive = false;
//指定資料轉送類型為二進位
ftpReq.UseBinary = true;
//上傳檔案時通知伺服器檔案的大小
ftpReq.ContentLength = fi.Length;
// 緩衝大小設定為2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
try
{
//開啟一個檔案流去讀上傳的檔案
FileStream fs = fi.OpenRead();
//把上傳的檔案寫入流
Stream strm = ftpReq.GetRequestStream();
//每次讀檔案流的2kb
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0) // 流內容沒有結束
{
// 把內容從file stream 寫入 upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception e)
{
}
'方法二
FileInfo file = new FileInfo("G:/www.111cn.net/室內設計01.jpg");
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(file.Name));
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(file.FullName);
Response.End();
}