繁体   English   中英

在只读模式下使用OpenXML打开锁定的文件

[英]Open locked file with OpenXML in read only mode

当我尝试打开一个锁定的文件时,如下所示:

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)

如何以只读模式打开文件而忽略锁定标志? 我也想避免在文件未在另一个程序中打开的情况下创建锁定标志,以便可以进一步编辑该文件。

尝试传递流而不是字符串(文件路径)。 您还可以使用文件流类来打开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
            }
        }
    }

来源: OpenXML并以只读模式打开文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM