C# reading an open text file in less than 10 lines

comments

There are times when you want to read a text file that is in use – or as i have had many times, code you have recently execute hasn’t fully let go of the file when you go to read it – when you copy something to a directory and the AV scans it or any other times when you want a file’s contents but don't want to have to worry about locks.

This seems like a really simple thing to do and it is, so some people would say not worth a post – but i like posting code snippets that i think are handy for fellow Googlers so enjoy :-)

 

string strFilePath = "C:\test.txt";
string strFileContents = string.Empty;

using (var fileStream = new FileStream(importPath, FileMode.Open, FileAccess.Read))
{
    using (var textReader = new StreamReader(fileStream))
    {
        strFileContents = textReader.ReadToEnd();
    }
}

Please be aware that this will not work for files that have been marked by a process as to not be shared then this will still not work, but the point of me posting this code is more for those instances when the file shouldn’t be locked but is (those odd occasions that seem to be more common than odd)