How do I open a file that is opened in another application

前端 未结 4 1210
广开言路
广开言路 2020-12-09 09:15

I have an winforms application that loads in excel files for analysis. Currently, in order to open the excel file the file must not be already open in excel otherwise a File

4条回答
  •  庸人自扰
    2020-12-09 09:48

    How are you trying to open the file?

    If you are trying to open it for read/write then you'll get the exception. If you are trying to open it for read only then you should be OK.

    var file = File.Open("file.xls", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    

    This will only work if Excel has opened the file with FileShare.Read set to allow other applications (i.e. your's) to have access to the file. If this isn't set then Excel will have opened the file with exclusive access. Note: I don't think this is the case as you can open an Excel file (in Excel) for read if someone else has it open for edit.

    UPDATE - OK I didn't test this properly until after darin's comments. You need the FileShare.ReadWrite flag despite the help indicating that it's for subsequent file openers. Not even FileShare.Read is good enough, which I find even odder.

提交回复
热议问题