0

I have been trying for too long to open an Excel file in a C# application created in Visual Studio 2012. I finally found that I need to provide the full path name to the Excel file, even though it exists in the same folder as the executable. Why is that?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application ExcelApp = new Excel.Application();
            try
            {
                MessageBox.Show("Current directory: " + Directory.GetCurrentDirectory());
                if (File.Exists("PLC01.xls"))
                {
                    MessageBox.Show("Target file exists.");
                }
                else
                {
                    MessageBox.Show("Target file does not exist.");
                }
                Excel.Workbook workbook = ExcelApp.Workbooks.Open(Directory.GetCurrentDirectory() + "\\PLC01.xls");

                // Excel.Workbook workbook = ExcelApp.Workbooks.Open("PLC01.xls");
                workbook.Close();
                MessageBox.Show("Book opened and closed.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
    }
}

This version works. But if I comment out the first call to Open() and uncomment the second, which only gives the file name and not the full path, I am told that the file can't be found, even though the "File exists" message box appears, verifying its existence.

Vityata
  • 42,633
  • 8
  • 55
  • 100
ROBERT RICHARDSON
  • 2,077
  • 4
  • 24
  • 57

1 Answers1

2

https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getcurrentdirectory?view=netframework-4.8

Directory.GetCurrentDirectory -

"Gets the current working directory of the application"

"The application" here is your C# executable: the launched Excel application instance is not running in the same context as your C# executable and so its "current directory" isn't necessarily the same.

If you know the full path, just pass that to Excel - no need to try to pass only the file name.

FYI - GetCurrentDirectory may not be the most robust way to locate your Excel file

How can I get the application's path in a .NET console application?

Tim Williams
  • 154,628
  • 8
  • 97
  • 125