我上传到FTP的文件的C#问题

Nez*_*zir 3 c# ftp

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

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

我使用此代码上传到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();
Run Code Online (Sandbox Code Playgroud)

Rex*_*x M 8

这段代码:

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

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

尝试使用ReadAllBytes之类的东西:

byte[] fileContents = File.ReadAllBytes("filepath");
Run Code Online (Sandbox Code Playgroud)