Upload a file with FTP in C# : The format of the U

2020-04-23 05:51发布

问题:

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.