Upload a file with FTP in C# : The format of the URI could not be determined

不想你离开。 提交于 2020-01-21 20:31:46

问题


I'm trying to upload a file with ftp in C#. for the moment, i try to do it locally:

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();
}

I get the following error: (see above) The format of the URI could not be determined

Thanks for your help


回答1:


I think you are missing protocol: should be ftp://127.0.0.1/ instead of 127.0.0.1/. What's more, I suggest you to encode part of url that is stored in filePath. f.e:

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

You need to reference System.Web assembly to use UrlEncode. More here.



来源:https://stackoverflow.com/questions/25093869/upload-a-file-with-ftp-in-c-sharp-the-format-of-the-uri-could-not-be-determine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!