Using StreamReader without locking the file in C#

I was using the StreamReader class to read the contents of a text file. I was under the assumption (well I know its a bad

thing)  that because I am only reading the contents of the file, the file would be available for other applications to read or write. Guess what, i was wrong. The StreamReader class does maintain a lock on the file until you call the Close() method. So to not have the lock, we have to explicitly set up the sharing mode.

FileStream fs = new FileStream(@”c:\test.txt”, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
txtContents.Text = sr.ReadToEnd();
sr.Close();

Technorati Tags: ,,

6 Responses

  1. Exactly what I needed! thanks.

  2. Thank you. Solved my issue too!

  3. Thank you. This helped me to fix my issue.
    My issue was user should able to rename or delete the file at any time from file system and I was using TextReader object to read data from file but sometime file is getting locked by IIS.
    I used FileStream object and FileShare.Delete as sharing mode. It works.

  4. Thanks!

  5. Thanks. Concise and in time.

  6. Thank you very much ! this solved my problem too !

Leave a Reply