2017-07-19 85 views
2

我有ň文件遠程文件夾,我需要在另一個遠程文件複製的內容。我想它可以通過流來完成,這是我的嘗試:多個遠程文件複製到另一個遠程文件通過HttpWebRequest的C#

  WebRequest destRequest = WebRequest.Create(destFile); 
      destRequest.Method = "PUT"; 
      destRequest.Headers.Add("x-ms-blob-type", "BlockBlob"); //just an example with Azure blob, doesn't matter 


      using (Stream destStream = destRequest.GetRequestStream()) 
      { 
       string sourceName = "mysourcefolder"; 

       int blockSize = 8388608; //all the files have the same lenght, except one (sometimes) 
       for (int i = 0; i < n; i++) 
       { 
        string source = sourceName + i; 
        WebRequest sourceRequest = WebRequest.Create(source); 
        destRequest.Method = "GET"; 
        HttpWebResponse destResp = (HttpWebResponse)destRequest.GetResponse(); 
        using (Stream sourceStream = destResp.GetResponseStream()) 
        { 
         sourceStream.CopyTo(destStream, blockSize); 
        } 
       } 

       Console.Write("ok"); 
      } 

     } 
     catch (Exception e) 
     { 
      Console.Write("nope !"); 
     } 

有我的代碼中多個問題:

1)我必須指定在我的PUT請求的lenght。可能是blockSize*n,因爲我對此沒有例外;

2)如果是這樣的話,我仍然是例外Cannot close stream until all bytes are written。這是什麼意思?

+0

我GESS您的要求越來越超時嘗試設置 'destRequest.Timeout;'' destRequest.ReadWriteTimeout;' –

回答

1

目前已在資源和dest請求混亂。 我已經添加了對變化線條的評論。

 WebRequest destRequest = WebRequest.Create(destFile); 
     destRequest.Method = "PUT"; 
     destRequest.Headers.Add("x-ms-blob-type", "BlockBlob"); //just an example with Azure blob, doesn't matter 
     using (Stream destStream = destRequest.GetRequestStream()) 
     { 
      string sourceName = "mysourcefolder"; 
      //int blockSize = 8388608; //all the files have the same lenght, except one (sometimes) //all the files have the same lenght, except one (sometimes) 
      for (int i = 0; i < n; i++) 
      { 
       string source = sourceName + i; 
       WebRequest sourceRequest = WebRequest.Create(source); 
       destRequest.Method = "GET"; 

       //HttpWebResponse destResp = (HttpWebResponse)destRequest.GetResponse(); 
       //using (Stream sourceStream = destResp.GetResponseStream()) 

       // you need source response 
       HttpWebResponse sourceResp = (HttpWebResponse)sourceRequest.GetResponse(); 
       using (Stream sourceStream = sourceResp.GetResponseStream()) 
       { 
        sourceStream.CopyTo(destStream); 
       } 
      } 
      // The request is made here 
      var destinationResponse = (HttpWebResponse) destRequest.GetResponse(); 
      //Console.Write("ok"); 
      Console.Write(destinationResponse.StatusCode.ToString()); 
     } 
+0

我得到'INT塊大小=(int)的sourceStream.Length NotSupportedException異常;'。唯一的例外是'該流不支持查找operations' –

+1

它可以調用'sourceStream.CopyTo(destStream)''沒有blockSize'。它是正確的還是我有問題? –

+0

是的,它是正確的。 – levent