Keeping a file locked between open and save with EPPLUS

63 Views Asked by At

Just looking for some advice for the best way to open an existing excel file, carry out some process on the data and then save it again while prevent others making edits to the excel file between my load and save.

I think I'm best using the FileStream approach.

If I close the stream them immediately call File.WriteAllBytes the file is saved. However, if I try and get the byte array then write the stream before closing the stream the file doesn't save. I know the GetAsByteArray() closes the package but why would that prevent me writing a FileStream?

using (var package = new ExcelPackage())
{
    using (var stream = new FileStream(_fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
    {
        package.Load(stream);

        //DO MY LOGIC STUFF

        //byte[] data = package.GetAsByteArray();
        //stream.Write(data, 0, data.Length);

        stream.Close();
        File.WriteAllBytes(_fileName, package.GetAsByteArray());
    }
}
1

There are 1 best solutions below

1
Charlieface On BEST ANSWER

However, if I try and get the byte array then write the stream before closing the stream the file doesn't save. I know the GetAsByteArray() closes the package but why would that prevent me writing a FileStream?

It's nothing to do with the GetAsByteArray() function, it's because the stream is still holding the file open, preventing another function from opening a new handle to it and writing it.

You need to reuse the stream you have already.

using (var package = new ExcelPackage())
using (var stream = new FileStream(_fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
    package.Load(stream);

    //DO MY LOGIC STUFF

    byte[] data = package.GetAsByteArray();

    stream.Position = 0;  // seek back to the beginning
    stream.SetLength(data.Length);
    stream.Write(data, 0, data.Length);
}