2

我使用以下源代码上传文件 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();
    }
4

3 回答 3

5

不要将二进制文件作为文本读取。使用Stream.CopyTo方法(如果不能使用 .Net 4.0,则使用等效代码)

 using(StreamReader sourceStream = ...){
   using(Stream requestStream = request.GetRequestStream())
   {
     sourceStream.CopyTo(requestStream);
   }
 }
于 2012-09-29T04:54:51.890 回答
0

您可以尝试使用处理原始字节的 BufferedStream。

于 2012-09-29T04:56:19.690 回答
0

在我的情况下,我无法按照 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();
}
于 2014-11-13T13:10:44.540 回答