.net, C#, Code, Microsoft, Technical

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: ,,
Advertisements

13 thoughts on “Using StreamReader without locking the file in C#

  1. 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.

  2. Thanks a lot, you helped me very much! Even better than calling the “close” method, would be to use the FileStream inside a “using” statement:

    using (FileStream fs = new FileStream(…))
    {
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s