Andrey
Andrey

Reputation: 60115

Open file in Silverlight doesn't work while OpenRead works

In-browser application.

I have a standard code for opening Open File Dialog, then reading file using dlg.File.OpenRead(). Now the problem comes if that file is opened with Excel. The opening failed, because internally it does following:

public FileStream OpenRead()
{
    new FileIOPermission(FileIOPermissionAccess.Read, this.FullPath).Assert();
    return new FileStream(this.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false);
}

To access file opened in Excel you have to use FileShare.ReadWrite. Ok, there is Open method, so I write:

dlg.File.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

And it gives error: "File operation not permitted. Access to path 'xyz' is denied". I checked what Open does internally:

public FileStream Open(FileMode mode, FileAccess access, FileShare share)
{
    return new FileStream(this.FullPath, mode, access, share);
}

Almost the same except requesting FileIOPermission, which in turn is internal and you can't use it in code.

So the question is, how to make this Open work? Or how can you open file with ReadWrite sharing?

Upvotes: 2

Views: 942

Answers (1)

AnthonyWJones
AnthonyWJones

Reputation: 189555

The answer is: you can't. The OpenFileDialog will only give you read access to the file in question. Similarly the SaveFileDialog only gives you write access. You don't get to control the level of sharing so you can't specify share ReadWrite.

You will need to ask the user to close the Excel file first before continuing as part of handling this error.

Upvotes: 2

Related Questions