Click here to Skip to main content
15,883,835 members
Articles / Programming Languages / C# 5.0
Tip/Trick

Open associated files with C# program

Rate me:
Please Sign up or sign in to vote.
4.89/5 (7 votes)
21 Aug 2014Apache2 min read 38.5K   1.2K   14   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:

Image 1

2. Step-Write the code

Illustrating the operation of the program:

Image 2

The Program.cs is as follows

C#
[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.

C#
/// <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.

C#
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:

C#
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

Image 3

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.

C#
//file path
        public string path = null;

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

C#
//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:

C#
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).

Image 4

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


Written By
Student
Hungary Hungary
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralImages Pin
Akhil Mittal20-Aug-14 19:36
professionalAkhil Mittal20-Aug-14 19:36 
Questionimages broken Pin
Andreas Gieriet20-Aug-14 10:57
professionalAndreas Gieriet20-Aug-14 10:57 

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

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