将文件上传到名称中包含特殊字符的ftp文件夹

时间:2017-01-03 06:54:56

标签: c# .net ftp

我正在尝试在FTP文件夹上传文件,但收到以下错误。

  

远程服务器返回错误:(550)文件不可用(例如,   找不到文件,没有访问权限)

我使用以下示例来测试:

    // Get the object used to communicate with the server.
    string path = HttpUtility.UrlEncode("ftp://host:port//01-03-2017/John, Doe S. M.D/file.wav");
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
    request.Method = WebRequestMethods.Ftp.UploadFile;

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

    // Copy the contents of the file to the request stream.
    StreamReader sourceStream = new StreamReader(@"localpath\example.wav");
    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();
  • 我可以在父文件夹01-03-2017上传文件,但不能在目标文件夹ROLLINS, SETH S. M.D中上传文件,其中明显包含特殊字符。
  • 我可以使用FileZilla上传文件
  • 我试过HttpUtility.UrlEncode,但没有帮助

感谢您的时间和帮助。

3 个答案:

答案 0 :(得分:2)

使用类似的东西:

string path = HttpUtility.UrlEncode("ftp://96.31.95.118:2121//01-03-2017//ROLLINS, SETH S. M.D//30542_3117.wav");

或者您可以使用以下代码形成Uri并将其传递给webrequest。

var path = new Uri("ftp://96.31.95.118:2121//01-03-2017//ROLLINS, SETH S. M.D//30542_3117.wav");

答案 1 :(得分:2)

您需要在URL路径中对空格(可能是逗号)进行编码,例如:

string path =
    "ftp://host:port/01-03-2017/" +
    HttpUtility.UrlEncode("John, Doe S. M.D") + "/file.wav";

实际上,你得到:

ftp://host:port/01-03-2017/John%2c+Doe+S.+M.D/file.wav

答案 2 :(得分:2)

代码适用于C#控制台应用程序,但在Web Api Action中不起作用。我无法找到原因。

所以我使用了一个免费的库。

从其中一个可用示例中发布示例代码here

所以我通过FluentFtp使用了Nuget libary。

using System;
using System.IO;
using System.Net;
using FluentFTP;

namespace Examples {
    public class OpenWriteExample {
        public static void OpenWrite() {
            using (FtpClient conn = new FtpClient()) {
                conn.Host = "localhost";
                conn.Credentials = new NetworkCredential("ftptest", "ftptest");

                using (Stream ostream = conn.OpenWrite("01-03-2017/John, Doe S. M.D/file.wav")) {
                    try {
                        // istream.Position is incremented accordingly to the writes you perform
                    }
                    finally {
                        ostream.Close();
                    }
                }
            }
        }
    }
}

同样,如果文件是二进制文件,StreamReader should not be used,如此处所述。

相关问题