47

I've been using File.ReadAllText() to open a CSV file, but every time I forget to close the file in Excel, the application throws an exception because it can't get access to the file.

(Seems crazy to me, I mean the READ in ReadAllText seems pretty clear)

I know that there is File.Open with all the bells and whistles, but is there an 'intermediate' method which doesn't involve messing around with buffers and char arrays?

2 Answers 2

70

I think you just want the following:

using (var fileStream = new FileStream("foo.bar", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var textReader = new StreamReader(fileStream))
{
    var content = textReader.ReadToEnd();
}
 

The FileAccess.Read parameter is what is important, to indicate that you only want to read the file. Of course, even to do this, the file must have been opened by Excel in read-share mode (see the FileShare enum in .NET). I haven't tested, so I can't guarantee that Excel does this, though I would expect it does.

[edit] Here's a method version:

static string ReadAllText(string file)
{
    using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var textReader = new StreamReader(fileStream))
    return textReader.ReadToEnd();
}
4
  • Thanks, what is the shortest thing I can put between the {} to get the whole string out of the file? (I did say I was lazy)
    – Benjol
    Sep 7, 2009 at 13:25
  • @Noldorin, thanks. That was the missing link. I looked at all the methods available on FileStream, couldn't understand.
    – Benjol
    Sep 7, 2009 at 14:02
  • 5
    @Noldorin: For info, I got round to trying it, you have to include the FileShare.ReadWrite argument to get it to work with Excel.
    – Benjol
    Sep 8, 2009 at 7:05
  • @Benjol: Ah, that makes sense I guess. Good to know anyway.
    – Noldorin
    Sep 8, 2009 at 11:30
1

If you want to specify file sharing flags in order to open a file that's in use, you're stuck with File.Open().

1
  • 1
    It's Excel that's opening the file, so the OP can't control this. He can only hope Excel does open it in read-share mode, and open it read-only himself.
    – Noldorin
    Sep 7, 2009 at 12:27

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.