2013-04-11 59 views
1

我下載一個文件用這種方法從中讀取:下載一個文件,並在同一時間

WebClient WC = new WebClient(); 
WC.DownloadFile(url, filePath); 

,我想的是,在同一時間與讀取文件在同一時間:

var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None); 

,但我得到八方通:

The process cannot access the file 'filePath' because it is being used by another process. 

有可能下載和閱讀在同一時間?

編輯

我現在與下載文件:

var req = (HttpWebRequest)HttpWebRequest.Create(url); 
       var fileStream = new FileStream(filePath, 
        FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); 

       using (var resp = req.GetResponse()) 
       { 
        using (var stream = resp.GetResponseStream()) 
        { 
         byte[] buffer = new byte[0x10000]; 
         int len; 
         while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) 
         { 
          fileStream.Write(buffer, 0, len); 
         } 
        } 
       } 

,仍然得到錯誤....

+1

不該文件需要寫入磁盤?你總是可以將它下載到內存並讀取流。 – 2013-04-11 14:40:23

+4

要做類似*的事情,您應該使用原始的'HttpWebRequest' /'GetResponseStream'並在每個塊到達時(通過任何「讀取」方法)處理每個塊。 – 2013-04-11 14:41:22

+0

可以將每個塊下載並寫入文件? – MTA 2013-04-11 14:43:08

回答

3
var req = (HttpWebRequest)HttpWebRequest.Create(url); 
using (var resp = req.GetResponse()) 
{ 
    using (var stream = resp.GetResponseStream()) 
    { 
     byte[] buffer = new byte[0x10000]; 
     int len; 
     while ((len = stream.Read(buffer, 0, buffer.Length))>0) 
     { 
      //Do with the content whatever you want 
      // ***YOUR CODE*** 
      fileStream.Write(buffer, 0, len); 
     } 
    } 
} 
+0

我應該如何定義文件流? – MTA 2013-04-11 14:56:47

+0

我定義它是這樣的:'var fileStream = new FileStream(filePath, FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite);'。並且仍然出現錯誤 – MTA 2013-04-11 14:59:49

+0

'進程無法訪問文件filePath,因爲它正在被另一個進程使用。「# – MTA 2013-04-11 15:05:42

0

試試這個方法:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://www.domain.com/file.txt"); 
HttpWebResponse response = (HttpWebResponse) request.GetResponse(); 

var stream = response.GetResponseStream(); 
byte[] buffer = new byte[8192]; 
int bytesRead = 0; 
while ((bytesRead = stream.Read(buffer, 0, 8192)) > 0) 
{ 
    // handle your raw data 
    // you needed raw data = buffer[0 to bytesRead - 1] 

} 
stream.Close(); 
response.Close(); 
+0

我編輯我的帖子.. – MTA 2013-04-11 15:01:28

相關問題