I have url to download csv file. I want to check file exists or not before i download it. I did try using HttpWebRequest but it didnot work out. Am i doing anything wrong or is there better option to check file exists or not before download.
public static void Main()
{
var fileUrl = "https://xxxxxxxxxxxxxx/npw/FinanceReport/ReturnFinancialReportCSV?rpt=FRY9C&id=1123944&dt=20240331";
bool isTrue = URLExists(fileUrl);
if (isTrue)
{
Console.WriteLine("Downloading file");
try
{
var location = "C:\Users\Downloads\FRY9C\";
var fileSaveUrl = location + "testFile.csv";
WebClient cln = new WebClient();
cln.UseDefaultCredentials = true;
cln.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
cln.Headers.Add("user-agent", "Only a test!");
cln.DownloadFile(fileUrl, fileSaveUrl);
}
catch (Exception ex)
{
}
}
}
public static bool URLExists(string url)
{
bool result = false;
WebRequest webRequest = WebRequest.Create(url);
webRequest.Timeout = 1200; // miliseconds
webRequest.Method = "HEAD";
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)webRequest.GetResponse();
result = true;
}
catch (WebException webException)
{
}
finally
{
if (response != null)
{
response.Close();
}
}
return result;
}
when I try to download the file when there is no file I am getting csv file with below data inside.