Windows Forms: How to check if file exists on Server in C#
By FoxLearn 9/7/2020 10:44:25 AM 3.76K
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.
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.
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024
What Are RESTful Web Services?
02/19/2024