C# 使用C下载文件#
我有一些代码可以从网站下载文本文件。当请求的文件不存在时,我的应用程序将下载一个包含html内容的文本文件。我需要过滤此html内容(如果请求的文件不存在,则不应下载包含html内容的文本文件),并且只需要下载具有正确内容的文本文件。下面是我的代码C# 使用C下载文件#,c#,C#,我有一些代码可以从网站下载文本文件。当请求的文件不存在时,我的应用程序将下载一个包含html内容的文本文件。我需要过滤此html内容(如果请求的文件不存在,则不应下载包含html内容的文本文件),并且只需要下载具有正确内容的文本文件。下面是我的代码 string FilePath = @"C:\TextFiles\" + FileName + String.Format("{0:00000}", i) + ".TXT"; Directory.CreateDirectory(Path.GetDir
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);
}
}
请告知假设
clientx
是HttpWebRequest
,然后检查响应的状态码:
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);
}
}
}
我建议你应该测试一下代码 如果文件存在并被传输给您,您可能会收到200“OK”代码,或者收到404“Not Found”代码 尝试: 编辑: 您需要将WebResponse转换为HttpWebResponse(请参阅) 尝试:
您还可以使用
WebClient
而不是HttpWebRequest
:
var client = new WebClient();
client.DownloadFile("http://someurl/doesnotexist.txt", "doesnotexist.txt");
如果文件不存在,这将引发
System.Net.WebException
。如果找不到文件,是否需要显示html页面?否,不应下载html页面。实际上它不是一个html页面。包含html内容的文本文件是HttpWebRequest:当我使用HttpWebResponse=clientx.GetResponse()时,我收到一条错误消息:无法将类型“System.Net.WebResponse”隐式转换为“System.Net.HttpWebResponse”。存在显式转换(是否缺少转换?)请参阅我的编辑,尝试使用HttpWebResponse=(HttpWebResponse)clientx.GetResponse()代码>是;但仍在下载包含html内容的文件。在网站上有一些文本文件,其中有一些歌曲。当请求的文件存在时,它将被下载,当不存在时,应用程序将下载包含网页html内容的文本文件。我需要解决这个问题看起来服务器没有发送404 Not Found
,所以您必须解析内容-为“不存在”的文件发送哪些内容?
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);
}
}
}
}
var client = new WebClient();
client.DownloadFile("http://someurl/doesnotexist.txt", "doesnotexist.txt");