Search code examples
c#file-iofile-in-use

Opening a file that's in use by another process


I've looked at several solutions to reading a file that's already in use by another process, but none of them seem to work for me.

The file I'm trying to read is an XML file that contains configuration settings that I need to extract.

Here's what I have tried:

using (var stream = File.Open("\\\\2008r2\\c$\\ProgramData\\location\\siteConfig.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(stream))
{
    // Actions you perform on the reader.
    while (!reader.EndOfStream)
    {
        Console.WriteLine(reader.ReadLine());
    }
}

This seems to work for just about everyone else, I don't know what I'm doing wrong! Is my file locked in a different manner and cannot be accessed even to read?

Help much appreciated!

Dave


Solution

  • From your comment, the original process has opened the file with FileShare.None. From MSDN:

    Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.

    The original process has an exclusive lock on it so you won't be able to read from it unless the FileShare enumeration is changed from None or the file is closed.