gpt4 book ai didi

c# - 使用 C# 上传到服务器后,Zip 文件已损坏

转载 作者:可可西里 更新时间:2023-11-01 09:00:19 26 4
gpt4 key购买 nike

我正在尝试使用 C# (Framework 4)上传 zip 文件到服务器,下面是我的代码。

string ftpUrl = ConfigurationManager.AppSettings["ftpAddress"];
string ftpUsername = ConfigurationManager.AppSettings["ftpUsername"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl + "Transactions.zip");
request.Proxy = new WebProxy(); //-----The requested FTP command is not supported when using HTTP proxy.
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
StreamReader sourceStream = new StreamReader(fileToBeUploaded);
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();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();

zip 文件已成功上传,但是当我尝试从服务器(手动)打开 zip 文件时,它显示Unexpected end of archive 错误。
对于文件压缩,我使用 Ionic.zip dll。在传输 zip 文件之前,我能够成功提取。

感谢任何帮助。谢谢。

最佳答案

问题是:

StreamReader sourceStream = new StreamReader(fileToBeUploaded);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());

StreamReader(以及任何 TextReader)用于文本 数据。 zip 文件不是文本数据。

只需使用:

byte[] fileContents = File.ReadAllBytes(fileToBeUploaded);

这样您就不会将二进制数据视为文本,因此它不应该被破坏。

或者,不要将它们全部单独加载到内存中 - 只需流式传输数据:

using (var requestStream = request.GetRequestStream())
{
using (var input = File.OpenRead(fileToBeUploaded))
{
input.CopyTo(requestStream);
}
}

另请注意,您应该对所有这些流使用 using 语句,而不是仅仅调用 Close - 这样即使发生异常,资源也会被释放抛出。

关于c# - 使用 C# 上传到服务器后,Zip 文件已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com