简体   繁体   中英

Cyrillic in the file name when upload to ftp C #

I am writing a program that uploads a file to remote ftp server. However, downloaded files sometimes contain Cyrillic. The contents of the file load correctly, but the name is distorted. I understand that this is due to the encoding. I tried to use Encoding.GetEncoding(1251).GetString(Encoding.GetEncoding(1251).GetBytes(file.FileName)) and other encodings. Does not help. At the same time, the php script that is stored on the same ftp correctly uploads files with cyrillic letters.

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"

I tried to use HttpUtility.UrlEncode(filePath) . Nothing helps. Tell me, please, how to deal with this?

Solution found. After scrolling through a few more forums, I came across the following solution:

Through NuGet Package Management install the package System.Net.FtpClient . Then we write the following code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM