Using EPPlus with a MemoryStream

后端 未结 8 1125
离开以前
离开以前 2020-12-05 06:05

I am using EPPlus to generate an XLSX file in C#. As soon as I instantiate the ExcelPackage with a memory stream - I get the error:

\"A disk error occ

8条回答
  •  半阙折子戏
    2020-12-05 06:50

    I faced with the same issue when tried to open existing excel file and spent couple days with it. In my case I received mentioned exception "A disk error occurred during a write operation. (Exception from HRESULT: 0x8003001D (STG_E_WRITEFAULT))" due to encryption.

    I was able to read .xlsx file by passing password. In my case empty string "" was enough.

    in your case please try to initialize package using constructor with password:

    public ExcelPackage(Stream newStream, string Password)
    
    package = new ExcelPackage(stream, "");
    

    Have a look into ExcelPackage source code http://epplus.codeplex.com/SourceControl/latest#EPPlus/ExcelPackage.cs

    There is a method

    private void Load(Stream input, Stream output, string Password) 
    

    which is used to load excel file.

    private void Load(Stream input, Stream output, string Password) 
    

    ...

    if (Password != null)
    
    {
      Stream encrStream = new MemoryStream();
      CopyStream(input, ref encrStream);
      EncryptedPackageHandler eph = new EncryptedPackageHandler();
      Encryption.Password = Password;
      ms = eph.DecryptPackage((MemoryStream)encrStream, Encryption);
    }
    else
    {
      ms = new MemoryStream();
      CopyStream(input, ref ms);
     }
    

    ...

    Code will try to decrypt excel stream even if password is empty, BUT NOT NULL.

    However if you try to initialize package for file that is not encrypted you will have exception:

    'The stream is not an valid/supported encrypted document.'

提交回复
热议问题