Nick_F
Nick_F

Reputation: 1121

System.IO.IOException: The process cannot access the file 'somefile.txt' because it is being used by another process

I am trying to open a file in read-only mode. The file is created by another application that is still running and probably it is kept open by that application. However, I am able to open the file using a text editor such as Notepad. Why can't read from the file in read-only mode?

        string file = @"c:\temp\somefile.txt";
        FileInfo fi = new FileInfo(file);  
        
        int len = (int)fi.Length;

        char[] chars = new char[len];
        var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
        
        int numBytesToRead = (int)fs.Length;
        int numBytesRead = 0;               
        
        using (var sr = new StreamReader(fs))
        {
            int n = sr.Read(chars, numBytesRead, len);
        }

Upvotes: 1

Views: 1026

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239654

You have to use one of the overloads of the FileStream constructor that accepts a FileShare parameter.

Basically, all of the open file handles have to agree - your FileAccess has to be compatible with their FileShare and your FileShare has to be compatible with their FileAccess (of course, I'm using .NET names here but these map to core Windows concepts common to all programs).

It seems likely you'll want to make your FileShare ReadWrite, to maximize the chances of interoperating with the other program, if you don't know what access it's using.

Upvotes: 3

Related Questions