When I try to open a file that is locked, like this:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
... code stripped for clarity ...
// false stands for read only mode
spreadsheetDocument_ = SpreadsheetDocument.Open(fileName_, false);
I get this exception:
System.IO.IOException: 'The process cannot access the file 'file.xlsx' because it is being used by another process.'
Full stack trace:
System.IO.IOException
HResult=0x80070020
Message=The process cannot access the file 'file.xlsx' because it is being used by another process.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync)
at MS.Internal.IO.Zip.ZipArchive.OpenOnFile(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
at System.IO.Packaging.ZipPackage..ctor(String path, FileMode mode, FileAccess access, FileShare share, Boolean streaming)
at System.IO.Packaging.Package.Open(String path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.OpenCore(String path, Boolean readWriteMode)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable, OpenSettings openSettings)
at DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(String path, Boolean isEditable)
How can I open the file in read only mode and ignore the lock flag? I also want to avoid creating a lock flag if the file is not open in another program, so that the file can be edited further.
Try to passing a stream instead of string (file path). You can also use a File stream class to open the Excel file.
Console app snippet:
static void Main(string[] args)
{
using (var fileStream = new FileStream(@"path", FileMode.Open,FileAccess.Read, FileShare.ReadWrite))
{
using (var spreadSheetDocument = SpreadsheetDocument.Open(fileStream, false))
{
//Implementation
}
}
}
User contributions licensed under CC BY-SA 3.0