将文件从本地计算机复制到ftp服务器c

时间:2014-09-22 13:05:54

标签: c# ftp

我需要从本地计算机将一些txt文件复制到ftp服务器。我使用以下代码。 (摘自:http://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.xxxx.com/");

    request.Method = WebRequestMethods.Ftp.UploadFile;

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential("username", "paswword");

    // Copy the contents of the file to the request stream.
    StreamReader sourceStream = new StreamReader(@"E:\log.txt");
    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();
    }

但是我导致"请求的URI对于此FTP命令无效"错误。我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:0)

您在URI处缺少文件名。例如:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.xxxx.com/log.txt");

好好看看你使用的例子。注意 test.htm

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");