views:

53

answers:

1

I am reading file with text contents on it.

sample dictionary.txt contents: aa abaca abroad apple

Snippet A:

Dim path as String = Server.MapPath("dictionary.txt");
Dim dictionary() as String = {}
Try
{
    dictionary = File.ReadAllLines(path)
}
Catch ex as Exception

End Try

Snippet B:

Dim path as String = Server.MapPath("dictionary.txt");
Dim dictionary As New List(Of String)
Using  fs As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
    Using sr As StreamReader = New StreamReader(fs)
        While Not sr.EndOfStream
            dictionary.Add(sr.ReadLine().Trim())
        End While
    End Using
End Using

In Snippet A, I seldom encounter an an error "File is used by another process". In Snippet B, I haven't encounter the same error yet.

Basically, I want to make sure that I can handle/prevent this error. Does Snippet B, solves the problem, if not is there other way so that I can prevent this error.

BTW, this a web application and I am expecting multiple users.

Thanks

+1  A: 

The second sample is more robust towards this problem, but not perfect. If the file is opened exclusively, or locked by an external process this will still fail. Unfortunately, thats just a fact of life on windows systems. It is possible to avoid this by using low level api calls, but the above method is generally sufficient in most normal cases.

GrayWizardx