上传到 ftp 服务器的文件为什么损坏了?

Files uploaded to ftp server, corrupted why?

文件上传成功,但文件已损坏。 请检查我的代码并解决我的问题。 我认为我的问题在这一行:

 byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());;
string ftpurl = "ftp://IP";
            string ftpusername = "u09z0fyuu"; // e.g. username
            string ftppassword = "Yamankatita1@"; // e.g. password

            string PureFileName = new FileInfo(file_name).Name;
            String uploadUrl = String.Format("{0}/{1}/{2}", ftpurl, "PDPix", file_name);
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // This example assumes the FTP site uses anonymous logon.  
            request.Credentials = new NetworkCredential(ftpusername, ftppassword);
            request.Proxy = null;
            request.KeepAlive = true;
            request.UseBinary = true;
            request.UsePassive = true;
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // Copy the contents of the file to the request stream.  
            StreamReader sourceStream = new StreamReader(_mediaFile.Path);
            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();
            _ = DisplayAlert("Upload File Complete, status {0}", response.StatusDescription,"OK");

您说过您正在尝试上传 图像文件。您不能将它们视为 UTF8,因为它们是 二进制数据 并且未使用 UTF8 编码。您需要将二进制数据视为二进制数据

可以直接读取字节

byte[] fileContents = File.ReadAllBytes(_mediaFile.Path);

说明

UTF8 无法将 byte (0x00 - 0xFF) 的所有可能值表示为字符并将它们再次返回为二进制格式。我们可以通过以下代码观察这一点:

byte[] input = new byte[8];
RNGCryptoServiceProvider.Create().GetBytes(input);

Console.WriteLine(string.Join(", ", input.Select(i => i)));

string tmp = System.Text.Encoding.UTF8.GetString(input); // interpret arbitrary bianry data as text
// the data is corrupted by this point
byte[] result = System.Text.Encoding.UTF8.GetBytes(tmp); // convert the text back to a binary form (utf8-encoded)
Console.WriteLine(string.Join(", ", result.Select(i => i)));

Try it online

这里我们生成 8 个随机字节,打印它们的值,尝试将它们解释为 string,将该字符串转换回字节,并打印它们的新值。

对于以下 8 个字节:

16, 211, 7, 253, 207, 91, 24, 137

结果我们得到了以下字节:

16, 239, 191, 189, 7, 239, 191, 189, 239, 191, 189, 91, 24, 239, 191, 189

就这样,我们的数据被破坏了!长话短说:不要对二进制数据使用文本编码。