Easiest way to read text file which is locked by another application

前端 未结 2 2145
借酒劲吻你
借酒劲吻你 2020-12-17 08:32

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\'

相关标签:
2条回答
  • 2020-12-17 09:00

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

    0 讨论(0)
  • 2020-12-17 09:09

    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.

    0 讨论(0)
提交回复
热议问题