Reputation: 444
I have some code to download a text file from a website. When the requested file does not exist, my application downloads a text file which has html content. I need to filter this html content (should not download a text file with html content if the requested file does not exist) and need to download only text files which has the correct content. Below is my code.
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);
}
}
Please advice
Upvotes: 2
Views: 13529
Reputation: 6854
I would suggest you ought to test the ReponseCode.
You would expect a 200 "OK" code if the file exists and is transmitted to you, or a 404 "Not Found" code.
Try:
var response = clientx.GetResponse();
HttpStatusCode code = response.StatusCode;
if (code == HttpStatusCode.OK)
{
//get and download stream....
}
EDIT:
You need to cast the WebReponse into a HttpWebResponse (see http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx)
Try:
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);
}
}
}
}
Upvotes: 1
Reputation: 66398
Assuming clientx
is HttpWebRequest
then just check the StatusCode of the response:
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);
}
}
}
Upvotes: 2
Reputation: 26792
You can also use WebClient
instead of HttpWebRequest
:
var client = new WebClient();
client.DownloadFile("http://someurl/doesnotexist.txt", "doesnotexist.txt");
This will throw a System.Net.WebException
if the file does not exist.
Upvotes: 3