[英]C# - File is corrupt after uploaded to server
我使用以下源代碼上傳excel和pdf文件,但是將文件移至服務器后,文件已損壞。 我認為問題在於編碼過程Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
,但我不知道如何解決。
public static void sampleUpload()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://100.165.80.15:21/output/Group Dealer, Main Dealer, Zone, Branch, and Destination Report_20120927105003.pdf");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("toc", "fid123!!");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("D:\\Group Dealer, Main Dealer, Zone, Branch, and Destination Report_20120927105003.pdf");
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();
}
不要將二進制文件讀取為文本。 使用Stream.CopyTo方法(或等效代碼,如果您不能使用.Net 4.0)
using(StreamReader sourceStream = ...){
using(Stream requestStream = request.GetRequestStream())
{
sourceStream.CopyTo(requestStream);
}
}
您可以嘗試使用處理原始字節的BufferedStream。
在我的情況下,我無法使用Alexei在他的回答中建議的Stream.Copy,因為我使用的是.NET Framework 2.0,而我只使用Stream來讀取二進制文件,因為Streamreader設計為僅讀取文本文件:
public static void sampleUpload()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://100.165.80.15:21/output/Group Dealer, Main Dealer, Zone, Branch, and Destination Report_20120927105003.pdf");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("toc", "fid123!!");
// Copy the contents of the file to the request stream.
byte[] b = File.ReadAllBytes(sourceFile);
request.ContentLength = b.Length;
using (Stream s = request.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.