使用C#下载文件

时间:2011-11-23 07:59:51

标签: 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);

    }
}

请咨询

3 个答案:

答案 0 :(得分:3)

您也可以使用WebClient代替HttpWebRequest

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

如果文件不存在,这将抛出System.Net.WebException

答案 1 :(得分: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);
        }
    }
}

答案 2 :(得分: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);
            }
        } 
    }
}