Sunday, 24 July 2011

Check Existence of File in ASP.NET and C#


This tutorials shows how we can verify if a file exists or not before executing code relating to said file. C# version.

Checking if a file exists before executing certain lines of codes can be very useful. It can prevent error messages caused by trying to manipulate a file that isn't there, for example. Using System.IO, we can check to see if a file exists in a certain directory with ease.

using System.IO;

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

The ASPX page will look something like this:

<form id="form1" runat="server">
Search for a file (inc. extension to see if it exists in the media directory.<br />
Hint: try delete.gif<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Go See" /><br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

The logic will check to see if there is any text in the textbox, when the button is clicked, first and foremost. If there is text present, it will check to see if this text is a file in the media folder. The user will be notified if it exists as a file or not.
The code-behind will look something like this:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
doesFileExist(TextBox1.Text);
}

public void doesFileExist(string searchString)
{
if (TextBox1.Text != "")
{
string imageFolder;
imageFolder = Server.MapPath("/media/") + searchString.ToString();
if (File.Exists(imageFolder))
{
Label1.Text = "File <b>" + searchString + "</b> <u>does</u> exist in '/media/' folder.";
}
else
{
Label1.Text = "File <b>" + searchString + "</b> <u>does not</u> exist in '/media/' folder.";
}
}
else
Label1.Text = "Please enter some text.";
}
}

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment