将文件上传到FTP目的地被破坏一次(Uploading files to FTP are corru

2019-06-24 00:11发布

我创建一个简单的拖放文件和上传,自动对FTP的Windows应用程序

和我使用MSDN代码上传文件到FTP。

该代码是非常直截了当:

// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("{0}{1}", FTP_PATH, filenameToUpload));
request.Method = WebRequestMethods.Ftp.UploadFile;

// Options
request.UseBinary = true;
request.UsePassive = false;

// FTP Credentials
request.Credentials = new NetworkCredential(FTP_USR, FTP_PWD);

// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(fileToUpload.FullName);
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();
writeOutput("Upload File Complete!");
writeOutput("Status: " + response.StatusDescription);

response.Close();

并且得到上传到FTP

问题是 ,当我看到在浏览器上的文件,或者只需下载并尝试看看它放在桌面上,我得到:

我已经使用request.UseBinary = false;request.UsePassive = false; 但它并没有缝做任何形式的任何好。

什么我发现是,原来的文件有122KB lenght并在FTP(和下载后),它具有219KB ...

我究竟做错了什么?

顺便说一句,在uploadFileToFTP()方法在内部运行BackgroundWorker ,但我真的不认为有什么差别的事情...

Answer 1:

你不应该使用一个StreamReader,但只有一个流中读取二进制文件。

StreamReader的设计为只读的文本文件。

试试这个:

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


Answer 2:

该问题是由代码中的二进制数据,字符数据和回二进制数据进行解码引起的。 不要这样做。


使用UploadFile方法的的WebClient类 :

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential(FTP_USR, FTP_PWD);
    client.UploadFile(FTP_PATH + filenameToUpload, filenameToUpload);
}


文章来源: Uploading files to FTP are corrupted once in destination