Как я открываю файл, который открыт в другом приложении

Это лучший способ сгенерировать .gitignore через здесь

.

22
задан Calanus 26 June 2009 в 09:34
поделиться

4 ответа

Вы можете попробовать передать FileShare.ReadWrite при открытии файла:

using (var stream = new FileStream(
       @"d:\myfile.xls", 
       FileMode.Open, 
       FileAccess.Read, 
       FileShare.ReadWrite))
{

}
30
ответ дан 29 November 2019 в 04:57
поделиться

SpreadsheetGear для .NET может читать книги, пока они открыты в Excel. Вот код, который мы используем для этого (обратите внимание, что мы блокируем весь файл после открытия, чтобы Excel или любое другое приложение не могло писать, пока мы находимся в процессе чтения):

stream = new System.IO.FileStream(path,
    System.IO.FileMode.Open,
    System.IO.FileAccess.Read,
    System.IO.FileShare.ReadWrite,
    SG.CompoundDocumentIO.Storage.OpenBufferLength);
try
{
    stream.Lock(0, stream.Length);
}
catch
{
    // .NET 1.1 requires cast to IDisposable
    ((IDisposable)stream).Dispose();
    throw;
}

Заявление об ограничении ответственности: Я владею SpreadsheetGear LLC

1
ответ дан 29 November 2019 в 04:57
поделиться

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.

6
ответ дан 29 November 2019 в 04:57
поделиться

Попробуйте сделать копию уже открытого файла, прочтите ее и удалите. Чтобы проверить, открыт ли уже файл, попробуйте прочитать и обработать исключение, выполнив копирование, чтение, сброс.

0
ответ дан 29 November 2019 в 04:57
поделиться
Другие вопросы по тегам:

Похожие вопросы: