Click here to Skip to main content
Click here to Skip to main content
Go to top

Open associated files with C# program

, 21 Aug 2014
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Apache License, Version 2.0

Share

About the Author

Magyar András
Student
Hungary Hungary
No Biography provided
Follow on   Google+

Comments and Discussions

 
GeneralImages Pinmvp Akhil Mittal 20-Aug-14 19:36 
Questionimages broken PinprofessionalAndreas Gieriet20-Aug-14 10:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 21 Aug 2014
Article Copyright 2014 by Magyar András
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid