【问题标题】:Cyrillic in the file name when upload to ftp C #上传到ftp C#时文件名中的西里尔字母
【发布时间】:2020-07-14 14:03:24
【问题描述】:

我正在编写一个将文件上传到远程 ftp 服务器的程序。但是,下载的文件有时包含西里尔字母。文件内容正确加载,但名称失真。我知道这是由于编码。 我尝试使用Encoding.GetEncoding(1251).GetString(Encoding.GetEncoding(1251).GetBytes(file.FileName)) 和其他编码。没有帮助。同时,存储在同一个ftp上的php脚本正确上传西里尔字母的文件。

public void FtpUpload(IFormFile file, string filePath)
{
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://xxx.xxx.xx.xxx/" + filePath);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential("username", "pass");
        byte[] fileBytes;
        if (file.Length > 0)
        {
            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                fileBytes = ms.ToArray();
            }
        }
        else return;

        request.ContentLength = fileBytes.Length;
        using (Stream request_stream = request.GetRequestStream())
        {
            request_stream.Write(fileBytes, 0, fileBytes.Length);
            request_stream.Close();
        }
}

filePath = "Тест.pdf"

我尝试使用HttpUtility.UrlEncode(filePath)。没有什么帮助。请告诉我,如何处理?

【问题讨论】:

    标签: c# file-upload encoding ftpwebrequest cyrillic


    【解决方案1】:

    找到解决方案。在浏览了更多论坛后,我遇到了以下解决方案:

    通过NuGet Package Management 安装包System.Net.FtpClient。 然后我们编写如下代码:

    public void FtpClientUpload(IFormFile file, string filePath)
        {
            FtpClient ftp = new FtpClient();
            ftp.Host = "xxx.xxx.xx.xxx";
            ftp.Credentials = new NetworkCredential("username", "pass");
            ftp.Encoding = Encoding.GetEncoding(1251);
    
            using (var remote = ftp.OpenWrite( filePath, FtpDataType.Binary))
                file.CopyTo(remote);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      相关资源
      最近更新 更多