2010-10-05 64 views
-2

可能重複下載前1000個字節的文件:
Download the first 1000 bytes使用C#

我需要用C#從互聯網上下載的文本文件。文件大小可以很小,我需要的信息始終在前1000個字節內。

這是我到目前爲止。我發現服務器可能會忽略範圍標題。有沒有辦法限制streamreader只讀取前1000個字符?

string GetWebPageContent(string url) 
{ 
    string result = string.Empty; 
    HttpWebRequest request; 
    const int bytesToGet = 1000; 
    request = WebRequest.Create(url) as HttpWebRequest; 

    //get first 1000 bytes 
    request.AddRange(0, bytesToGet - 1); 

    // the following code is alternative, you may implement the function after your needs 
    using (WebResponse response = request.GetResponse()) 
    { 
     using (StreamReader sr = new StreamReader(response.GetResponseStream())) 
     { 
      result = sr.ReadToEnd(); 
     } 
    } 
    return result; 
} 
+1

是。來自同一用戶的完全相同的問題,並在那裏接受了答案 – 2010-10-05 22:04:42

+0

我發佈了一些限制在其他問題中讀取的流的代碼 – 2010-10-05 22:11:02

回答

1

你可從流的前1000個字節,然後解碼從字節的字符串:

using (WebResponse response = request.GetResponse()) 
{ 
    using (Stream stream = response.GetResponseStream()) 
    { 
     byte[] bytes = new byte[bytesToGet]; 
     int count = stream.Read(bytes, 0, bytesToGet); 
     Encoding encoding = Encoding.GetEncoding(response.Encoding); 
     result = encoding.GetString(bytes, 0, count); 
    } 
} 
+0

該流寫入字符[] – 2010-10-05 22:10:31

+0

@Luke Schafer,你是什麼意思? 「該流」與其他流沒有區別。 Stream.Read方法需要一個字節[],而不是char []。檢查文檔之前,你downvote ... – 2010-10-05 22:14:15

+0

你一定在StreamReader.Read混淆。我在這裏沒有使用StreamReader ... – 2010-10-05 22:16:04

0

而不是使用request.AddRange()可通過如你所說的一些服務器被忽略,讀取1000個字節(1 KB = 1024字節),然後關閉它。這就像您在收到1000字節後從服務器斷開連接一樣。代碼:

int count = 0; 
int result = 0; 
byte[] buffer = new byte[1000]; 
// create stream from URL as you did above 

do 
{ 
    // we want to read 1000 bytes but stream may read less. result = bytes read 
    result = stream.Read(buffer, 0, 1000); // Use try around this for error handling 
    count += result; 
} while ((count < 1000) && (result != 0)); 
stream.Dispose(); 
// now buffer has the first 1000 bytes of your request 
+0

使用該解決方案,如果響應短於1000字節,它會永遠循環... – 2010-10-05 22:23:27

+0

!=(結果!= 0)添加。謝謝 – Xaqron 2010-10-05 23:05:24