How to make a file load in my program when a user double clicks an associated file.
- by Edward Boyle
I assume in this article that file extension association has been setup by the installer. I may address file extension association at a later date, but for the purpose of this article, I address what sometimes eludes new C# programmers.
This is sometimes confusing because you just don’t think about it — you have to access a file that you rarely access when making Windows forms applications, “Program.cs”
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
There are so many ways to skin this cat, so you get to see how I skinned my last cat.
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 mainf = new Form1();
if (args.Length > 0)
{
try
{
if (System.IO.File.Exists(args[0]))
{
mainf.LoadFile= args[0];
}
}
catch
{
MessageBox.Show("Could not open file.", "Could not open file.", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Application.Run(mainf);
}
}
It may be easy to miss, but don’t forget to add the string array for the command line arguments:
static void Main(string[] args) this is not a part of the default program.cs
You will notice the mainf.LoadFile property. In the main form of my program I have a property for public string LoadFile ... and the field private string loadFile = String.Empty; in the forms load event I check the value of this field.
private void Form1_Load(object sender, EventArgs e)
{
if(loadFile != String.Empty){
// The only way this field is NOT String.empty is if we set it in
// static void Main() of program.cs
// LOAD it however it is needed OpenFile, SetDatabase, whatever you use.
}
}