开发者

How to read a file which is opened in c#? [duplicate]

开发者 https://www.devze.com 2023-02-14 00:01 出处:网络
This question already has answers here: 开发者_开发百科 Closed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_开发百科 Closed 11 years ago.

Possible Duplicate:

Read file which is in use?

I have an mvvp-wpf aplication.. And I use infragistics to read the file. When the file is open..and if I try to read the file through application I get an exception.

One way to solve this is ...ask user to close the file .

Is there any other solution ?

Thanks in advance !


Try to open it with the least privileges, e.g. don't request an exclusive read or write lock.


You could try:

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, System.IO.FileShare.ReadWrite)

to open the file in a non-exclusive mode.


The type of the exception could help here, but what I can says is this : when a program opens a file it gives two parameters to the OpenFile api :

  • Desired access : read, write, both ?
  • Share mode : exclusive, share read, share write, share delete ?

Depending on how the file is open the first time, you may or may not open it a second time : if it's already open with share mode exclusive for example, you won't be able to open it a second time to do something else.


After some search I've found a workaround for this problem: Create a FileStream object with the file name, and FileMode.Open, FileAccess.Read, FileShare.ReadWrite as parameters.

Looks like Excel is keeping a write lock on the XLS file while it's running and has the file open, so we need to open the file in ReadWrite fileshare mode.

You can pass in this FileStream object to the Workbook.Load method as parameter, instead of the file name, and the program will then be able to read the file while it's also open in Excel.

FileStream selectedFileStream = new FileStream(currentFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Workbook internalWorkBook = Workbook.Load(selectedFileStream);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号