In C# Open A File Programmatically

Open A File Programmatically Banner Image

Introduction

When testing an app or writing programs that generate files, you may want to automate opening the file in code than manually opening those files. The normal process may go like this. Run the program then once the program is complete and then open windows explorer and navigate to where the file is located. C# provides an process start method to open the file.

Process Start Example 1

The following code checks if the file exists on the hard drive before trying to open the file programmatically.

string textFilePath = @"C:\Temp\testFile.xlsx"; //file location
FileInfo excelFileInfo = new FileInfo(textFilePath);
if (excelFileInfo.Exists)
{
    System.Diagnostics.Process.Start(excelFileInfo.FullName);
}

This will start the process that is associated with the file. In this case, Excel will open the .xlsx file and that way you won't have open have to double-click to open it.

Example 2

This next example still uses the Process class but it is other to configure the process class. See the example below.

string textFilePath = @"C:\Temp\testFile.xlsx"; //
Process process = new Process();
process.StartInfo.FileName = textFilePath;
process.StartInfo.UseShellExecute = true;
process.Start(); 
Get Latest Updates