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();
Exactly what I needed! thanks.
Thank you. Solved my issue too!
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.
Thanks!
Thanks. Concise and in time.
Thank you very much ! this solved my problem too !
Thank you!!!! This is exactly what i needed. awesome!
Thanks! đ
Thanks!, you really help me!
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(…))
{
}
Excellent post. Solved my contention problem. Cheers.
Thanks a lot! đ
there is always need of closing connection when opening it…