Wednesday, November 09, 2005

Reading a file which is being accessed by another process

Ever come across the following error while trying to read a file? An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll Additional information: The process cannot access the file "xxx" because it is being used by another process. This error is thrown because another application (or process) is locking access to that file that you wish to access. If all you want to do is to read that file, then you would assume that using the StreamReader object should work. But, alas, its not that simple. What you need to do is to open the file as a fileStream, which allows you more opening parameters. You can then read the file normally by creating the StreamReader with the FileStream that you just opened. Here is what I do: using( FileStream fs = new FileStream("c:\test.txt", FileMode.Open,FileAccess.Read, FileShare.ReadWrite)) //this is what will allow you to access the file, even though its in use by another process { StreamReader sr = new StreamReader(fs); if (sr != null) { string curLine = null; while ((curLine = sr.ReadLine()) != null) { Console.WriteLine(curLine); } } }

No comments: