程式碼如下:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://帳號@ftp.XXXX.com.tw/ExcelFile.xls");
request.Method = WebRequestMethods.Ftp.UploadFile;
// FTP的帳密.
request.Credentials = new NetworkCredential("帳號", "密碼");
// 要上傳的檔案
StreamReader sourceStream = new StreamReader("ExcelFile.xls");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
如出現"227 Entering Passive Mode"的錯誤,
需在建立request之後加入request.UsePassive = false;
會發生這樣的錯誤是因為程式預設是使用被動式的連線,
當Server端也是被動式的連線就會發生錯誤,
所以將使用被動連線設定成false就解決了
程式碼參考網址:http://pdyurfof.pixnet.net/blog/post/27044025-c%23-%E4%B8%8A%E5%82%B3%E6%96%87%E4%BB%B6%E8%87%B3ftp
沒有留言:
張貼留言