在 .NET 要 FTP 上傳檔案,最精簡有效的做法莫過於使用 WebClient,例如:

using System;
using System.IO;
using System.Net;
 
public class CSharpLab
{
    public static void Test()
    {
        string userName = "ftpAccount";
        string password = "ftpPassword";
        string uploadUrl = "ftp://myFtpServerHost/someFolder/test.txt";
        byte[] data = new byte[] { 0x31, 0x32, 0x33 };
        WebClient wc = new WebClient();
        wc.Credentials = new NetworkCredential(userName, password);
        wc.UploadData(uploadUrl, data);        
    }
}

這個寫法在專案中廣泛運用多年都沒遇到什麼問題。近日同事在 FTP 上傳某一主機時,卻發生 553 File name not allowed 錯誤:System.Net.WebException: The remote server return an error: (553) File name not allowed

手動 FTP 登入上傳,確定路徑、權限都沒有問題。爬文發現,原來 Linux FTP Server 與 IIS FTP Server 存在行為差異

Linux FTP Server 不像 IIS 有共用的 FTP 根目錄,登入後會處於該帳號的使用者根目錄(例如:/home/username),因此對Linux FTP Server,ftp://myFtpServerHost/someFolder/test.txt 將指向 /user/home/someFoler/test.txt,如果要指向絕對路徑,需多加一根「/」,寫成 ftp://myFtpServerHost//someFolder/test.txt 。

過去面對的 FTP 主機都是 Windows 故沒發現,第一次遇上 Linux FTP 主機才學到這點。問題在修改 URL 多加 / 後排除,結案。


Comments

# by kinnie

太感謝了~ 我用ftp續傳軟體怎麼測都可以,用程式跑怎麼試都不行,原來是因為這個原因

Post a comment