2016-12-29 84 views
1

我想ftpupload一個zip文件與異步/ AWAIT模式:異步/等待ftpupload損害上傳的文件

private async void button2_Click(object sender, RoutedEventArgs e) 
    { 

     await processFtp(); 

    } 
    async Task processFtp() 
    { 
     string result = ""; 
     string ftpHost = "ftp://mysite/mysubdir"; 

     string ftpUser = "itsme"; 

     string ftpPassword = "mypw"; 

     string ftpfullpath = ftpHost + "/" + "OutdoorTest.zip"; 

     string fileToUpload = @"c:\temp\Outdoorbilder.zip"; 
     try 
     { 

      FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpfullpath); 
      request.Method = WebRequestMethods.Ftp.UploadFile; 

      request.Credentials = new NetworkCredential(ftpUser,ftpPassword); 
      request.UseBinary = true; 
      request.KeepAlive = false; 
      request.ReadWriteTimeout = 1000000; 
      request.Timeout = 1000000; 

      using (Stream requestStream = request.GetRequestStream()) 
      { 

       using (FileStream fs = File.OpenRead(fileToUpload)) 
       { 
        byte[] b = new byte[10 * 1024]; 
        int readLength = 0; 
        int sentLength = 0; 
        while ((readLength = fs.Read(b, 0, b.Length)) > 0) 
        { 
         await requestStream.WriteAsync(b, 0, b.Length); 
         int percentComplete = (int)((float)(sentLength += readLength)/(float)fs.Length * 100); 
         ftpprogress.Value = percentComplete; 
        } 
        requestStream.Close(); 
        requestStream.Flush(); 
       } 
      } 

      FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 
      response.Close(); 


      result = response.StatusDescription; 
     } 
     catch (WebException e) 
     { 

      result = e.Message; 
      if (e.Status == WebExceptionStatus.ProtocolError) 
      { 
       result = result + "Status Code : " + 
        ((FtpWebResponse)e.Response).StatusCode; 
       result = result + "\nStatus Description : " + 
        ((FtpWebResponse)e.Response).StatusDescription; 
      } 
     } 
     catch (Exception e) 
     { 
      result = e.Message; 
     } 


     MessageBox.Show(result); 
    } 
} 

的代碼似乎好工作,我得到一個226響應。但是ftp服務器上的壓縮文件比原來的壓縮文件大1000bytes,下載到移動android設備後無法打開/提取。

當我沒有異步/等待模式上傳時,上傳的文件在本地原始文件上與ftp服務器具有相同的大小。

這是怎麼發生的?

回答

3

這與async/await無關。

你的問題是,你沒有告訴上傳正確的大小。看看這兩條線:

while ((readLength = fs.Read(b, 0, b.Length)) > 0) 
{ 
    await requestStream.WriteAsync(b, 0, b.Length); 

你需要指定的WriteAsyc將讀取的量,而不是分配給字節的緩衝區量。至少最後一次讀取將返回小於緩衝區大小。

所以正確的代碼是:

while ((bytesRead = fs.Read(b, 0, b.Length)) > 0) 
{ 
    await requestStream.WriteAsync(b, 0, bytesRead);