Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Open associated files with C# program

0.00/5 (No votes)
21 Aug 2014 2  
Almost all of the basic functions of the program(browser, text editor, image editor, media player) that you can associate files with it and open it. I want a simple and effective method to show the arguments (associated files) to open. How to associate files with C# program?

Introduction

Almost all of the basic functions of the program(browser, text editor, image editor, media player) that you can associate files with it and open it. I want a simple and effective method to show the arguments (associated files) to open. How to associate files with C# program? I present the step by step procedure below.

1. Step-Create the general form

Create a new Windows Forms application in Visual Studio. Add menustrip(optional), toolstrip(optional), statusstrip(optional), and richtextbox controls to general form.

It should look like:

2. Step-Write the code

Illustrating the operation of the program:

The Program.cs is as follows

[STAThread] 
        static void Main(string[] args) 
        { 
        }

To be transformed into the main library to be able to recive arguments.

This part of the program will determine whether there is an argument: If the argument is not equal to zero and greater than zero, then there is an argument. generating a string variable that contains the argument. if a user opens a file in the program, it will be stored in the variable the path. then verify that the file exists. If no argument is specified, the program "normally" runs.

/// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        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))
                {
                    
                }
                
            }
                //without args
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }

Return to the Form1.cs file, make a public method that will open the associated file.

public void OpenFile(string filePath)
        {
 
    openStatus.Text = "Open file: " + filePath;
          Thread.Sleep(1000);
 
            string file = File.ReadAllText(filePath);
            richTextBox1.Text = file;
            openStatus.Text = "Ready";
        }

Now let us return to the Program.cs source file again. Create a new Form1, but it'll show you invite before the Open method, which read and displays the argument in the richtextbox.

The program has only one error: If the associated file does not exist does nothing. should be presented to the user with a message box that informs.

The Program.cs is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
 
namespace Associate
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        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 MainFrom = new Form1();
                    MainFrom.OpenFile(fileName);
                    Application.Run(MainFrom);
                }
                //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());
            }
        }
    }
}

Argument transfer splash screen via

Illustrating the operation of the program

Create splash screen form(download Office 2013 style splash screen: http://www.codeproject.com/Articles/804316/Office-Style-Splash-Screen) or use another one.

The splash screen source code, we create a public string variable, which will contain the path to the opened file.

//file path
        public string path = null;

Program.cs change the value of the variable in the argument.

//Check file exists
                if (File.Exists(fileName))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
 
                    Splash splash = new Splash();
                    splash.path = fileName;
                    Application.Run(splash);
                }

If the variable is not null, then invite the Open method.

The splash screen with full source code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
using Associate;
 
namespace Associate_with_splash_screen
{
    public partial class Splash : Form
    {
        //file path
        public string path = null;
 
 
        public Splash()
        {
            InitializeComponent();
 
            //Tasks
            //Starting
            tasks.Text = "Starting...";
            Thread.Sleep(1000);
 
 
 
            //start timer
            splashtime.Start();
        }
 
        public bool Isminimized = false;
 
        //Close Application
        private void close_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        //Minimize Application
        private void minimize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            Isminimized = true;
        }
        //Mouse hover and leave effects
        private void close_MouseHover(object sender, EventArgs e)
        {
            close.ForeColor = Color.Silver;
        }
 
        private void close_MouseLeave(object sender, EventArgs e)
        {
            close.ForeColor = Color.White;
        }
 
        private void minimize_MouseHover(object sender, EventArgs e)
        {
            minimize.ForeColor = Color.Silver;
        }
 
        private void minimize_MouseLeave(object sender, EventArgs e)
        {
            minimize.ForeColor = Color.White;
        }
 
        //Show MainForm(Form1)
        public void frmNewFormThread()
        {
 
            var frmNewForm = new Form1();
            if (Isminimized == true)
            {
                frmNewForm.WindowState = FormWindowState.Minimized;
            }
            else
            {
                frmNewForm.WindowState = FormWindowState.Maximized;
            }
 
            if(path != null)
            {
                frmNewForm.OpenFile(path);
            }
            Application.Run(frmNewForm);
        }
 
        private void splashtime_Tick(object sender, EventArgs e)
        {
            splashtime.Stop();
 
            var newThread = new System.Threading.Thread(frmNewFormThread);
            newThread.SetApartmentState(System.Threading.ApartmentState.STA);
            newThread.Start();
            this.Close();
        }
 
        private void Splash_FormClosed(object sender, FormClosedEventArgs e)
        {
 
        }
 
 
        private void Splash_MouseMove(object sender, MouseEventArgs e)
        {
 
        }
 
        private void Splash_MouseDown(object sender, MouseEventArgs e)
        {
 
        }
    }
}

3. Step-Checking the program:

Associate files, then open with program.

Give him an argument invalid file, let's look to react. Start cmd.exe, and start the example program with argument.

Example:

Command: start program.exe argument

Command: start iexplore.exe http://www.microsoft.com/

The latter command open the microsoft.com in the Internet Explorer browser(now the argument is the microsoft.com website).

Non-existent file is specified as an argument, so the program warns.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here