当我尝试打开已锁定的文件时,如下所示:
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);
我得到了这个例外:
System.IO.IOException: 'The process cannot access the file 'file.xlsx' because it is being used by another process.'
完整堆栈跟踪:
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)
如何以只读模式打开文件并忽略锁定标志?如果文件未在另一个程序中打开,我还想避免创建锁定标志,以便可以进一步编辑该文件。
答案 0 :(得分:1)
尝试传递流而不是字符串(文件路径)。您还可以使用文件流类打开Excel文件。
控制台应用代码段:
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
}
}
}