views:

90

answers:

2

I need to read a Windows file that may be locked, but I don't want to create any kind lock that will prevent other processes from writing to the file.

In addition, even if the file is locked for exclusive use, I'd like to see what's inside.

Although this isn't my exact use case, consider how to read a SQL/Exchange log or database file while it's in use and mounted. I don't want to cause corruption but I still want to see the insides of the file and read it.

+1  A: 

You can probably create a copy and read that, even if the file is locked.

Or maybe a StreamReader on a FileStream depending on how SQL opened the file?

new FileStream("c:\myfile.ext", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Chad
That could work... but a database is big. Maybe I need to know how Copy works, since I want that type of access.
MakerOfThings7
+5  A: 

You can do it without copying the file, see this article:

The trick is to use FireShare.ReadWrite (from the article):

private void LoadFile()
{
    try
    {
        using(FileStream fileStream = new FileStream(
            "logs/myapp.log",
            FileMode.Open,
            FileAccess.Read,
            FileShare.ReadWrite))
        {
            using(StreamReader streamReader = new StreamReader(fileStream))
            {
                this.textBoxLogs.Text = streamReader.ReadToEnd();
            }
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show("Error loading log file: " + ex.Message);
    }
} 
Kazar
@Kazar - I just posted a new question in response to seeing this: http://stackoverflow.com/questions/3560921/is-it-better-to-use-the-using-directive-in-c-or-the-dispose-method-does-th
MakerOfThings7