How can I download a file with Hebrew characters in its name from an ftp server via .net console application?

I am using a .net console application written in C# to download certain files from an ftp server routinely, it used to work properly until there was a file with Hebrew characters, named something like that:

1234--אבג.jpeg

so I've tried to download the same file using both chrome and FileZilla - and encountered no problems, with neither plain nor URL encoded version of the filename.

My problem is how to download the same file with my C# application

I have tried:

  • to escape the name as URL-encoded, worked for chrome but not my APP
  • to convert the string to utf-8
  • both System.Net.WebRequest and HttpClient
  • finding and taking the name from response of directory listing and pasting into the request, hoping it will have the proper format.

here is my code :

 public static string attachmentToFile(string name, string filename)
    {
        try
        {
      
            string ftpConnection = ConfigurationManager.AppSettings["FtpServer"].ToString();
            string ftpUser = ConfigurationManager.AppSettings["FtpUser"].ToString();
            string ftpPassword = ConfigurationManager.AppSettings["FtpPassword"].ToString();
            string attachmentPath = ConfigurationManager.AppSettings["attachmentFolder"].ToString();

            Directory.CreateDirectory(attachmentPath);

            attachmentPath += '\\' + name + Path.GetExtension(filename);


            FtpWebRequest attachmentRequest = (FtpWebRequest)WebRequest.Create(
                new Uri(ftpConnection + "/files_directory/" + filename)
                );


            attachmentRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
            attachmentRequest.Method = WebRequestMethods.Ftp.DownloadFile;

            FtpWebResponse response = (FtpWebResponse)attachmentRequest.GetResponse();
            var stream = response.GetResponseStream();
            FileStream saveStream = new FileStream(attachmentPath, FileMode.OpenOrCreate);
            //stream.Seek(0, SeekOrigin.Begin);
            stream.CopyTo(saveStream);
            saveStream.Close();
            return attachmentPath;
        }
        catch (Exception ex)
        {
            Logger.LogError(MethodBase.GetCurrentMethod(), ex, "failed downloading file from server: " + filename);
            return null;
        }
    }


Read more here: https://stackoverflow.com/questions/64402653/how-can-i-download-a-file-with-hebrew-characters-in-its-name-from-an-ftp-server

Content Attribution

This content was originally published by Michael Razgoner at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: