Diary of a ninja
A blog about Life, Code and Beating level 99 to brag to your mates...
C# reading an open text file in less than 10 lines

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)

{ 2 Responses... read them or add one below  }


Miron says November 10, 2009 aP 03:17PM
This is even shorter: string strFilePath = "C:\test.txt"; string strFileContents = string.Empty; strFileContents = File.ReadAllText(strFilePath )


Reply
Gravatar
Doug says November 10, 2009 aP 04:03PM
Hi mate. I think you'll find that will give you a file access error if another process is using the file. Cheers doug


Reply
Gravatar

Leave a Reply