Windows Forms: How to check if file exists on Server in C#

This post shows you How to check if file exists on Server in C#

Sometimes you need to check if the file exists before downloading it to your computer, you can follow this article.

Creating a simple windows forms application allows you to enter a url, then check if file exists on server in c# as shown below.

how to check if file exists in c#

Creating a FileExists method, we will use HttpWebRequest to create a request to web server, then use HttpWebResponse to get respone return from web server.

private bool FileExists(string url)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "HEAD";
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            return (response.StatusCode == HttpStatusCode.OK);
        }
    }
    catch
    {
        return false;
    }
}

If your StatusCode response is OK, we will return true, otherwise false.

Adding a click event handler to the Check button allows you to check if file exists on Server in c#.

private void btnCheck_Click(object sender, EventArgs e)
{
    bool result = FileExists(txtUrl.Text);
    if (result)
        MessageBox.Show("The file exists on the server.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    else
        MessageBox.Show("The file couldn't be found on the server.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

if the resulting value equals false, your file doesn't exist on the server.

Related Posts