Upload a file with encoding using FTP in C#

不羁的心 提交于 2019-12-03 06:13:28

Try this bit:

private static void up(string sourceFile, string targetFile)
{            
    try
    {
        string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
        string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
        string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
        ////string ftpURI = "";
        string filename = "ftp://" + ftpServerIP + "//" + targetFile; 
        FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
        ftpReq.UseBinary = true;
        ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
        ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

        byte[] b = File.ReadAllBytes(sourceFile);

        ftpReq.ContentLength = b.Length;
        using (Stream s = ftpReq.GetRequestStream())
        {
            s.Write(b, 0, b.Length);
        }

        FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();

        if (ftpResp != null)
        {
            MessageBox.Show(ftpResp.StatusDescription);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

You should be using a Stream to read binary files, not a StreamReader. StreamReader is designed to read text files only.

In your first code example, enable binary transfer: FtpWebRequest.UseBinary = true. Otherwise it will convert what it thinks are textual line endings between the various platform conventions (but are actually part of the image).

Your second snippet does it the right way. It uses FileStream, not StreamReader. StreamReader is only suitable for text files.

Jonathan

System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());

Don't do this unless your stream's contents are text. Change your function to accept a boolean parameter "binary", and use the latter, working method if that flag is set.

If you have this problem: The requested FTP command is not supported when using HTTP

you need set proxy in Null or Nothing.

ftpReq.Proxy = null;

You can see this blog.

http://mycodetrip.com/2008/10/29/fix-for-error-the-requested-ftp-command-is-not-supported-when-using-http-proxy_118/comment-page-1/#comment-2825

Thanks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!