簡體   English   中英

使用C#下載文件

[英]Downloading a file using C#

我有一些代碼可以從網站下載文本文件。 當請求的文件不存在時,我的應用程序將下載一個具有html內容的文本文件。 我需要過濾此html內容(如果所請求的文件不存在,則不應下載具有html內容的文本文件),並且僅需要下載具有正確內容的文本文件。 下面是我的代碼。

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);

    }
}

請指教

您也可以使用WebClient代替HttpWebRequest

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

如果該文件不存在,則將拋出System.Net.WebException

假設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);
        }
    }
}

我建議您應該測試ReponseCode。

如果文件存在並傳輸給您,您將期望輸入200個“確定”代碼,或者404個“未找到”代碼。

嘗試:

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

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

編輯:

您需要將WebReponse強制轉換為HttpWebResponse(請參閱http://msdn.microsoft.com/zh-cn/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);
            }
        } 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM