Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange error when opening Package for writing

Tags:

c#

.net

package

First things first, I'm using .NET 4.

I'm trying to write some files to a package, and I'm encountering something strange when I do this:

using (var package = Package.Open(filename, FileMode.OpenOrCreate, FileAccess.Write))
{
    // do something with package
}

Package refers to System.IO.Packaging.Package.

The weird thing is that Package.Open method throws an exception that says:

Cannot get stream with FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append when access is FileAccess.Read.

I found an old bug report from 2009 on Microsoft Connect: http://connect.microsoft.com/VisualStudio/feedback/details/392318/argumentexception-text-is-wrong

But it doesn't help.

So, anyone got an idea?

like image 212
Etienne de Martel Avatar asked May 04 '11 21:05

Etienne de Martel


Video Answer


1 Answers

I think I found the problem.

When I changed to code to do this:

using (var stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
{
    using (var package = Package.Open(stream))
    {
        // do something with package
    }
}

I got a pretty decent error message:

Cannot open package because FileMode or FileAccess value is not valid for the stream.

I think that's the "real" error message, and that someone, somewhere, simply mixed it up with that nonsensical one when doing the localization.

Then I changed the code for this:

// no FileAccess parameter
using (var package = Package.Open(file, FileMode.OpenOrCreate))
{
    // do something with package
}

And it no longer crashes, and seems to work properly.

like image 178
Etienne de Martel Avatar answered Sep 24 '22 13:09

Etienne de Martel