user9411650
user9411650

Reputation:

Is there a way to check wheather the c# program was opened by a file with associated extension?

I want to check if my C# program was opened by a file that has an associated extension. If the program was opened by that file it should execute that function:

public void openFile(String pathToFile) {
    if (File.Exists(pathToFile)) {
        int counter = 0;
        string line;

        StreamReader file = new System.IO.StreamReader(pathToFile);

        while ((line = file.ReadLine()) != null) {
            listBox1.Items.Add(line);
            counter++;
        }

        file.Close();
    }
}

I've already associated extension.
enter image description here

Upvotes: 0

Views: 70

Answers (1)

MikeH
MikeH

Reputation: 4395

If you're looking to find the file that was double clicked (or otherwise "executed") which launched your program:

In program.cs replace your static void Main() with static void Main(string[] args). This will allow you to see arguments that were passed to your program. The first argument (args[0]) will be the name of the file that was double clicked.

Here's a quick test I wrote:

static void Main(string[] args)
{

  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);
  for (int i = 0; i < args.Length; i++) MessageBox.Show("args[" + i.ToString() + "]: " + args[i]);
  Application.Run(new Form1(args));
}

Upvotes: 1

Related Questions