Sunday, 24 July 2011

Check Existence of File in ASP.NET and VB


This tutorials shows how we can verify if a file exists or not before executing code relating to said file. VB 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.

Imports System.IO

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

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>

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

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:

Imports System.IO

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
doesFileExist(TextBox1.Text)
End If
End Sub

Public Sub doesFileExist(ByVal searchString As String)
If TextBox1.Text <> "" Then
Dim imageFolder As String
imageFolder = Server.MapPath("/media/") & searchString.ToString()
If File.Exists(imageFolder) Then
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."
End If
Else
Label1.Text = "Please enter some text."
End If End Sub
End Class

Looking for the C#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment