Exception in opening a file that is already open

后端 未结 5 1056
迷失自我
迷失自我 2020-12-07 01:47

I am building an application in C# in which I have to open a CSV file to read data from it. I get an exception when I try to open the CSV file from C# when that file is alre

5条回答
  •  忘掉有多难
    2020-12-07 02:35

    I faced this problem some time back.

    You are missing the FileShare parameter. Without specifying that, if you open a file, it will be locked exclusively by your application. But since it's already been opened by Excel (or any other app), you will receive an exception.

    You can try using this - I think this will be your best bet -

    using (FileStream fs = File.Open(, FileMode.Open, FileAccess.Read, FileShare.Read))

    This code says: Hello Excel! If you may permit (read, not throw exception), I would like to read the file, though I will not try to own it and I know that you may modify it anytime.

    If this throws error, then Excel has denied you even the read access. Too bad then! All the best.

提交回复
热议问题