2011-11-23 71 views
2

我有一些代碼可以從網站下載文本文件。當請求的文件不存在時,我的應用程序會下載包含html內容的文本文件。我需要過濾這個html內容(如果請求的文件不存在,不應該下載包含html內容的文本文件),並且只需要下載具有正確內容的文本文件。以下是我的代碼。使用C下載文件#

string FilePath = @"C:\TextFiles\" + FileName + String.Format("{0:00000}", i) + ".TXT"; 
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); 
//MessageBox.Show(FilePath); 

using (FileStream download = new FileStream(FilePath, FileMode.Create)) 
{ 
    Stream stream = clientx.GetResponse().GetResponseStream(); 
    while ((read = stream.Read(buffer, 0, buffer.Length)) != 0) 
    { 

     download.Write(buffer, 0, read); 

    } 
} 

請指點

+0

如果找不到文件,您需要顯示一個html頁面嗎? – giftcv

+0

不,html頁面不應該下載。實際上它不是一個html頁面。 HTML內容的文本文件 – Kevin

回答

1

假設clientxHttpWebRequest然後就檢查響應的StatusCode:

HttpWebResponse response = (HttpWebResponse)clientx.GetResponse(); 
if (response.StatusCode != HttpStatusCode.OK) 
{ 
    MessageBox.Show("Error reading page: " + response.StatusCode); 
} 
else 
{ 
    string FilePath = @"C:\TextFiles\" + FileName + String.Format("{0:00000}", i) + ".TXT"; 
    Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); 
    //MessageBox.Show(FilePath); 
    using (FileStream download = new FileStream(FilePath, FileMode.Create)) 
    { 
     Stream stream = response .GetResponseStream(); 
     while ((read = stream.Read(buffer, 0, buffer.Length)) != 0) 
     { 
      download.Write(buffer, 0, read); 
     } 
    } 
} 
+0

是HttpWebRequest:當我使用HttpWebResponse響應= clientx.GetResponse()即時通訊有錯誤消息:\t不能隱式地將類型'System.Net.WebResponse'轉換爲'System.Net.HttpWebResponse'。存在明確的轉換(您是否缺少演員?) – Kevin

+0

請參閱我的編輯,嘗試讓'HttpWebResponse response =(HttpWebResponse)clientx.GetResponse();' –

+0

yes;但仍然下載帶有html內容的文件。在網站上有一些文本文件,其中有一些歌曲。當請求文件存在時被下載,當不存在時應用程序下載帶有該網頁的html內容的文本文件。我需要解決這個問題 – Kevin

1

我建議你應該測試ReponseCode。

如果文件存在併發送給您或404「未找到」代碼,您會期望得到200個「OK」代碼。

嘗試:

var response = clientx.GetResponse(); 
HttpStatusCode code = response.StatusCode; 

if (code == HttpStatusCode.OK) 
{ 
    //get and download stream.... 
} 

編輯:

您需要的WebReponse鑄造成一個HttpWebResponse(見http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx

嘗試:

using(HttpWebReponse response = (HttpWebResponse)clientx.GetResponse()) 
{ 
    if (response.StatusCode == HttpStatusCode.OK) 
    { 
     string FilePath = @"C:\TextFiles\" + FileName + String.Format("{0:00000}", i) + ".TXT"; 
     Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); 

     using (FileStream download = new FileStream(FilePath, FileMode.Create)) 
     { 
      Stream stream = clientx.GetResponse().GetResponseStream(); 
      while ((read = stream.Read(buffer, 0, buffer.Length)) !=0) 
      { 
       download.Write(buffer, 0, read); 
      } 
     } 
    } 
} 
3

你也可以使用WebClientHttpWebRequest代替:

var client = new WebClient(); 
client.DownloadFile("http://someurl/doesnotexist.txt", "doesnotexist.txt"); 

,這將拋出一個System.Net.WebException如果文件不存在。