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.