This little article explains a way to check if a file or path exists in code, without having to wait a long time for the result if the network is down or the path does not exist.
For example, in my particular case, I wanted a way to check for connectivity to the network before accessing the server file system. Scaling the internet I found some good C# examples (like this one: http://stackoverflow.com/questions/1232953/speed-up-file-exists-for-non-existing-network-shares)
However, the application I was working on was developed in VB.Net and the threading code is quite different between the languages.
The first problem I encountered was trying to pass a variable to the threading function. After some playing around, I was able to produce the following in VB.Net (based on the example in the link above) and using Visual Studio 2008.
Public Function PathExists(ByVal path As String, ByVal timeout As Integer) As Boolean Dim exists As Boolean = True Dim t As New Thread(DirectCast(Function() CheckPathFunction(path), ThreadStart)) t.Start() Dim completed As Boolean = t.Join(timeout) If Not completed Then exists = False t.Abort() End If Return exists End Function Public Function CheckPathFunction(ByVal path As String) As Boolean Return System.IO.File.Exists(path) End Function
Note: To use this method, you would call the function like done below, passing in an integer representing milliseconds before it stops trying to reach the path – in this case I have set it to 3 seconds.
If PathExists("\\BLAH\PATH\", 3000) Then ... End If
Hope this helps,
Stefan.
For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.