【问题标题】:C# problem with files which I upload to my FTP我上传到我的 FTP 的文件的 C# 问题
【发布时间】:2011-06-08 20:32:49
【问题描述】:

当我将文件上传到我的 FTP(zip 或 gif)文件时,我遇到了一个非常奇怪的问题。

我正在创建一个包含代码的 zip 文件并将其与代码一起上传到 FTP。当我在本地磁盘上创建这些文件类型时,我可以打开它们。但是,当我将其中任何内容上传到 FTP 并下载它时,会显示 .zip 文件的消息为“存档意外结束”,以及 .gif 文件类型在我下载它们并尝试在 XP Windows 图片和传真查看器中打开之后“绘图失败”:

我使用此代码上传到 FTP:

 FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.tim.com/" + fileName);
                request.Method = WebRequestMethods.Ftp.UploadFile;
            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential(ftpuser,ftppass);

            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader(filePath +"\\"+ fileName);
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;
            request.KeepAlive = false;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();

【问题讨论】:

  • Encoding.UTF8 是一种文本编码,您正在尝试读取文本中的二进制流,因此会出现问题。
  • 是的 :) 你是对的 Mike .. 我没有看到这条线 :D

标签: c# ftp


【解决方案1】:

这段代码:

StreamReader sourceStream = new StreamReader(filePath +"\\"+ fileName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());

您正在将字节流作为具有特定编码 (UTF8) 的文本读取...但 GIF 和 ZIP 是二进制文件,而不是文本文件。编码正在破坏它们。

尝试使用类似ReadAllBytes:

byte[] fileContents = File.ReadAllBytes("filepath");

【讨论】:

  • 为我工作。谢谢亲 :)
【解决方案2】:

您正在将二进制数据读取为字符串(假设为 utf8)并将其转换回字节数组。这是完全错误的。

【讨论】:

  • +1 - 尝试改用byte[] fileContents = File.ReadAllBytes(path)
猜你喜欢
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多