Home > Blockchain >  C# and ClosedXML :: How to throw/catch an exception when opening a nonexistent file?
C# and ClosedXML :: How to throw/catch an exception when opening a nonexistent file?

Time:07-01

I'm a Java coder learning C# for a new project. I have the following code which opens and reads an Excel spreadsheet:

using System.IO;
using ClosedXML.Excel;

public foo(string excelFilePath)
{
    var workbook = new XLWorkbook(new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
    // read and write to the file, etc...
}

This all works great, but I want the code to gracefully throw an exception if the file is misplaced or misnamed. Something like this:

using System.IO;
using ClosedXML.Excel;

public foo(string excelFilePath)
{
    var workbook = null;
    try
    {
        new XLWorkbook(new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
        // read and write to the file, etc...
    }
    catch(Exception ???)
    {
        System.Console.WriteLine("Gah!  I couldn't find \"" excelFilePath "\"");
    }
}

I've searched online, but I can't find any examples of doing this with new XLWorkbook() Did I pick the wrong function? Thank you.

CodePudding user response:

My advice would before even be throwing the exception check for the file existence, if there is a problem opening the file you can throw IO exception

   if (!File.Exists(excelFilePath))
        {
            Console.WriteLine("Gah!  I couldn't find file \""   excelFilePath   "\"");
            return;
        }
        var workbook = null;
        try
        {
            new XLWorkbook(new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
            // read and write to the file, etc...
        }
        catch (IOException ex)
        {
            Console.WriteLine(ex.Message);
            System.Console.WriteLine("Gah!  I can't open file \""   excelFilePath   "\"");
        }
     }
  • Related