How to Read Locked file in VB or C#

Have you ever got this error “File is being used by another process”

Just try this create simple textfile on disk (e.g. mydata.txt) and open it with Excel… This way its locked (This is my trick to mimic locking of file)

Now try to read file using below code while its opened by Exec.

Dim s As String = System.IO.File.ReadAllText("C:\demo.csv")

Above code will fail if you try to read file which is locked by some one else… But there is one trick you can do to read file which is locked….

Use below code now

VB.net

        Dim fs = New FileStream("C:\demo.csv", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
        Using sr = New StreamReader(fs)
            Console.Write("File content: " & sr.ReadToEnd)
        End Using

C#

 var fs = new FileStream(@"C:\demo.csv", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
        using (var sr = new StreamReader(fs)) {
            Console.Write("File Content:" + sr.ReadToEnd());
        }

Binary World is a Software Development company located in Atlanta, USA (since 2007). Binary World specialized in Business Intelligence, mobile, cloud computing and .Net Application Development.

Tagged with: ,
Posted in .net, C#, VB.net

Leave a Reply