Sometimes, in order to reduce our chance of error, when working with the filesystem in ASP.NET, we need to determine wether a file exists before performing an action on it.
The following short piece of code will enable us to test whether a file exists
Dim fs As New IO.FileInfo
if fs.fileexists then
'perform our action here
end if
Of course we are able to create this test as a function, making our code read more easily and providing reuse of the action
Function doesFileExist(ByVal FileFullPath As String) As Boolean
Dim fs As New IO.FileInfo(FileFullPath)
Return fs.fileexists
End Function
This function would be called as
if doesFileExist(server.mappath("counter.txt")) then
'our actions to, perhaps, read a counter
end if
A fuller example of checking to see whether a file exists is included below. Here we test to see whetehr a file exists. If it doesn't then we seed it with a value of 0. Following this we perform the usual action of reading the value in the file, incrementing it by one and then saving the file again.
Dim counterFile as string = server.mappath("counter.txt")
if not doesFileExist(counterFile ) then
objWriter = File.CreateText(sFile)
objWriter.Write("0") objWriter.Close
End if
Dim counter as integer
Dim sCounter as string
objReader = File.OpenText(counterFile )
sCounter = objReader.ReadToEnd()
objReader.Close
Counter = Cint(sCounter)
Counter = Counter + 1
sCounter = Counter.ToString
objWriter = File.CreateText(counterFile))
objWriter.Write(sCounter)
objWriter.Close
Similarly we are also able to test to see whether our directory exists, below is a suitable function:
Function doesFolderExists(ByVal FolderPath As String) As Boolean
Dim fd As New IO.DirectoryInfo(FolderPath)
Return fd.Exists
End Function
If our directory doesn't exist then we are able to create it using
Directory.CreateDirectory(Server.MapPath("janet.Guestbook"))
NAT November 2005