Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

winform application to launch and read from a file with custom extension

Tags:

c#

winforms

I am building a windows forms application using C# that needs to get launched when a user clicks on a file with custom extension(eg. filename.mycustomextension) I plan to put a url in the filename.mycustomextension file. when user clicks on this file, we winform application should launch and also read contents of this file. Is it possible to do this?

like image 336
user124118 Avatar asked Jan 27 '10 03:01

user124118


2 Answers

First and most obviously you'll need to associate the file extension with the application either by "open with" in the shell, through an installer or directly in the registry.

MSDN - Best Practices for File Associations

Then from there it's really pretty simple.


   static class Program
    {    
        [STAThread]
        static void Main()
        {
            string[] args = Environment.GetCommandLineArgs(); 
            string text = File.ReadAllText(args[1]);

            // ...
        }
    }

  • args[0] is the application path.
  • args[1] will be the file path.
  • args[n] will be any other arguments passed in.

Offhand I can't find any examples that show all of this together simply but Scott Hanselman has a nice example of loading files through a single instance WinForms application, about the same...

http://www.hanselman.com/blog/CommentView.aspx?guid=d2f676ea-025b-4fd6-ae79-80b04a34f24c

like image 186
JKG Avatar answered Sep 24 '22 14:09

JKG


Yes, it is possible.

The idea is that when your application is clicked, you modify the registry key, to associate the extension file with your application.

Here are the sketches:

  1. Use the FileAssociation class from here.
  2. Initialize it, set all the parameters.

Here is an example:

            var FA = new FileAssociation();
            FA.Extension = "blah";
            FA.ContentType = "application/blah";
            FA.FullName = "blah Project File";
            FA.ProperName = "blahFile";
            FA.AddCommand("open", string.Format("\"{0}\" \"%1\"", System.Reflection.Assembly.GetExecutingAssembly().Location));
            //"C:\\mydir\\myprog.exe %1");
            FA.IconPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            FA.IconIndex = 0;
            FA.Create();
like image 29
Graviton Avatar answered Sep 25 '22 14:09

Graviton