How to check if a file exists on a server using c# and the WebClient class

前端 未结 2 837
耶瑟儿~
耶瑟儿~ 2020-12-16 11:23

In my application I use the WebClient class to download files from a Webserver by simply calling the DownloadFile method. Now I need to che

2条回答
  •  情书的邮戳
    2020-12-16 12:18

    When you request file using the WebClient Class, the 404 Error (File Not Found) will lead to an exception. Best way is to handle that exception and use a flag which can be set to see if the file exists or not.

    The example code goes as follows:

    System.Net.HttpWebRequest request = null;
    System.Net.HttpWebResponse response = null;
    request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("www.example.com/somepath");
    request.Timeout = 30000;
    try
    {
        response = (System.Net.HttpWebResponse)request.GetResponse();
        flag = 1;
    }
    catch 
    {
        flag = -1;
    }
    
    if (flag==1)
    {
        Console.WriteLine("File Found!!!");
    }
    else
    {
        Console.WriteLine("File Not Found!!!");
    }
    

    You can put your code in respective if blocks. Hope it helps!

提交回复
热议问题