使用C#上传FTP文件:无法确定URI的格式

时间:2014-08-02 10:07:02

标签: c# ftpwebrequest

我试图在C#中使用ftp上传文件。目前,我尝试在本地进行:

static void Main(string[] args)
{
    UploadFileToFtp("C:\\Utilisateurs\\arnaud\\Bureau\\yhyhyyh.rtf","root","root");
}

public static void UploadFileToFtp(string filePath, string username, string password)
{
    var fileName = Path.GetFileName(filePath);
    var request = (FtpWebRequest)WebRequest.Create("127.0.0.1/" + fileName);<---ERROR

    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(username, password);
    request.UsePassive = true;
    request.UseBinary = true;
    request.KeepAlive = false;

    using (var fileStream = File.OpenRead(filePath))
    {
        using (var requestStream = request.GetRequestStream())
        {
            fileStream.CopyTo(requestStream);
            requestStream.Close();
        }
    }

    var response = (FtpWebResponse)request.GetResponse();
    Console.WriteLine("Upload done: {0}", response.StatusDescription);
    response.Close();
}

我收到以下错误:(见上文) 无法确定URI的格式

感谢您的帮助

1 个答案:

答案 0 :(得分:4)

我认为您缺少协议:应该是ftp://127.0.0.1/而不是127.0.0.1/。还有什么,我建议你编码存储在filePath中的部分网址。 f.e:

var encoded = HttpUtility.UrlEncode(filePath);
var request = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/" + encoded)

您需要引用 System.Web 程序集才能使用UrlEncode。更多here