简体   繁体   English

FTP在C#中返回损坏的文件,为什么?

[英]FTP in C# returning corrupted file, why?

I have this method to transfer files using a FTP Server: 我有这种方法使用FTP服务器传输文件:

private void TransferNeededFiles(IEnumerable<string> filenames)
{
    foreach (var filename in filenames)
    {
        var request = WebRequest.Create(new Uri(@"ftp://{0}/{1}".Fill(Config.ServerUri, filename))) as FtpWebRequest;

        if (request != null)
        {
            request.Credentials = new NetworkCredential(Config.Username, Config.Password);

            request.Method = WebRequestMethods.Ftp.DownloadFile;
            using (var streamReader = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                var fileStream = new FileStream(@"{0}/{1}".Fill(Config.DestinationFolderPath, filename), FileMode.Create);

                var writer = new StreamWriter(fileStream);
                writer.Write(streamReader.ReadToEnd());
                writer.Flush();
                writer.Close();

                fileStream.Close();
            }
        }
    }
}

A .gz file, included in the list of filenames, is always corrupted. 包含在文件名列表中的.gz文件始终已损坏。 When I try to copy from ftp using windows explorer, the file is not corrupted. 当我尝试使用Windows资源管理器从ftp复制时,该文件未损坏。 Do you know what is happening? 你知道发生了什么吗?

The problem is this line: 问题是这一行:

writer.Write(streamReader.ReadToEnd());

StreamReader.ReadToEnd() returns a Unicode encoded string. StreamReader.ReadToEnd()返回Unicode编码的字符串。 You want something that will read the stream byte for byte. 你想要的东西会读取字节的流字节。

Reader s and Writer s work with Unicode characters. ReaderWriter使用Unicode字符。 To transfer binary data you want to be working with raw bytes, so you should be using plain Stream s. 要传输您希望使用原始字节的二进制数据,因此您应该使用普通的Stream You can copy from one stream to another with a loop like the following: 您可以使用如下所示的循环从一个流复制到另一个流:

BufferedStream inputStream, outputStream;
byte[] buffer = new byte[4096];
int bytesRead;

while ((bytesRead = inputStream.Read(buffer)) > 0)
{
    outputStream.Write(buffer, 0, bytesRead);
}

A good thing about this is that it will also only use a fixed amount of memory rather than reading the entire file into memory at once. 这样做的一个好处是它也只会使用固定数量的内存,而不是一次将整个文件读入内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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