Error not raised when saving a file that is open and locked


#1

When you try to save a file that is already open in Excel (and therefore locked) you get the error.

System.Exception: Access denied because another user has the file open and locked… —> System.NullReferenceException: Object reference not set to an instance of an object.

The problem is that this exception isn’t raised to my app so that I can catch it with a try{}catch block.

For example, in the block of code below, I try to catch any and all Exceptions and it doesn’t work. I still get the error message above and I don’t want my end users to see this message. I would rather they get something a little more informative and not close the app. Am I doing something wrong or is this a bug?



string fn = saveFileDialog.FileName;
try
{
excel.Save(fn,FileFormatType.Default);
}
catch (System.NullReferenceException)
{
MessageBox.Show (“The file is already open and can’t be overwritten. Close the file in Excel or choose another file name.”);

}
catch (NotSupportedException)
{
MessageBox.Show (“Cannot write to file”);
}
catch (UnauthorizedAccessException)
{
MessageBox.Show (“Not authorized to write to file”);
}
catch (System.Exception e)
{
MessageBox.Show (e.ToString());
}


#2

Hi, thanks for your consideration.

I test your sample code. And the exception is caught in the last catch block.

You can try the following code:

catch(System.Exception e)
{
MessageBox.Show(e.Message);
}

or

catch(System.Exception e)
{
if(e.Message == “Access denied because another user has the file open and locked…”)
MessageBox.Show(“The file is already open and can’t be overwritten. Close the file in Excel or choose another file name.”);
else
MessageBox.Show(e.Message);
}


I mistyped a duplicate full stop. In next hotfix I will fix it. So the comparasion need to be changed to:

if(e.Message == “Access denied because another user has the file open and locked.”)