0

I am programming, in Microsoft's Visual Studio 2015, in C#.

I am trying to make an Windows Forms application which would be used to open simple .txt, or other type files, and edit them.

But the point being is i want to open my program with : Right click on .txt file->Open with->My program.

The question I have is this, how am I supposed to do that, if I only have the solution file of my program? And i don't really care, about opening the .txt files when my program is already running. I want to be able to start it, like i mentioned before.

I am using this program as a starting point, from where the next time i will be able to make a simple mp3 player, or such. And as far as i know, people don't usually start an mp3 player program, and then the mp3 player file they want to play. I hope that sheds some light on what i am trying to accomplish.

I have been searching for a solution, and i couldn't find it. Perhaps it is really easy, but for me, for now, it isn't. Your help is appreciated.

My Program.cs looks like this :

static void Main(string[] args)
        {
            //with args(user open file with the program)
            if(args != null && args.Length > 0)
            {
                string fileName = args[0];
                //check file exists
                if (File.Exists(fileName))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    Form1 MainForm = new Form1();
                    MainForm.OpenFile(fileName);
                    Application.Run(MainForm);
                }
                //the file does not exist
                else
                {
                    MessageBox.Show("The file does not exist!", "Error!",     MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                }
            }
            //without args
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
pnuts
  • 58,317
  • 11
  • 87
  • 139
Marin
  • 11
  • 7
  • To achieve what you describe, you have to have the mp3 playing control in your code so that all users need on your WinForm is to point to mp3 file. This is probably what you are looking for. http://stackoverflow.com/questions/15025626/playing-a-mp3-file-in-a-winform-application – yantaq Oct 20 '15 at 19:01
  • it still doesn't say anything about starting my solution the way i described, by starting file first – Marin Oct 20 '15 at 19:03
  • I think I understand your question better now and gave an answer below. I tested it and it works. again if this is not what you are trying to do then you may have to write to Registry for file association. http://stackoverflow.com/questions/69761/how-to-associate-a-file-extension-to-the-current-executable-in-c-sharp – yantaq Oct 20 '15 at 20:18

3 Answers3

1

If you're asking how to handle opening the file, try this:

-In your Form1.cs, overload your constructor by adding another definition.

public Form1(string fileName)
{
    InitializeComponent();
    openFileNow(fileName);
}

-Create the openFileNow method (async for extra goodness)

private async void openFileNow(string fileName)
    {
        try
        {
            if(fileName.EndsWith(".txt"))
            {
                //Obviously you'll do something different with an .mp3
                using (StreamReader reader = new StreamReader(fileName))
                {
                    txtEditBox.Text = await reader.ReadToEndAsync();
                }
            }
            else
            {
                MessageBox.Show("Can't open that file.");
            }
        }
        catch (IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }

-Edit your Program.cs to simply:

static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form1 MainForm;

        if (args != null && args.Length > 0)
        {
            MainForm = new Form1(args[0]);
        }
        else
        {
            MainForm = new Form1();
        }

        Application.Run(MainForm);

    }

In Visual Studio, under the project's properties, you can add Command line arguments in the "Debug" section.

If you want to associate a file extension with your application, you do that in the registry. You can do it in C#, but the ClickOnce settings will be so much cleaner.

Go to your project properties -> Publish -> Options -> FileAssociations

Edit - Note that if you intend to publish with ClickOnce, you'll need to change a few lines in your Program.cs:

string fileName = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
        if (fileName != null && fileName.Length > 0)
        {
            MainForm = new Form1(fileName);
        }
Zig
  • 2,603
  • 1
  • 14
  • 20
  • on .net 6, ClickOnce can't get arg, error message: Cannot resolve symbol 'ActivationArguments' – Ruyut Jul 12 '22 at 06:56
0

In your Form add a button1 (or change it to suit your need) and add the following logic.
whatever file you open, following logic will use your system default program to open them without further asking.

BTW, Form1 doesn't have OpenFile method , you may have gotten it from somewhere. you can remove it or add method definition.
MainForm.OpenFile(filename);

private void button1_Click(object sender, EventArgs e)
{
     var fileDialog1 = new OpenFileDialog
     {
          InitialDirectory = "c:\\",
          RestoreDirectory = true
     };

     if (fileDialog1.ShowDialog() == DialogResult.OK)
     {
          System.Diagnostics.Process.Start(fileDialog1.FileName);
      }
}

if this is not what you are trying to do then you may have to write to Registry for file association. I gave the link in the comment above.

yantaq
  • 3,968
  • 2
  • 33
  • 34
0

If you're simply looking to debug with file associations, try right-clicking a .txt file, Open With... (More Options) and navigate to your .exe from your project's debug folder, i.e.:

C:\VS Projects\MyProject\MyProject\bin\Debug\myProgram.exe

Obviously this is a temporary solution. Enjoy!

Zig
  • 2,603
  • 1
  • 14
  • 20