weiszam
weiszam

Reputation: 187

Open specific files with my c# application - like opening .doc files with Word

You can set Windows to open .doc files with Word or another application. How can I create such a c# applications, which can handle, if for excample I open a .txt file with that application? So the plan is: There's a information.kkk file wich is a text file and there's a number in it. I want my c# application (Visual Studio 2010) to receive that number if the file gets opened by it.

Upvotes: 1

Views: 5161

Answers (3)

weiszam
weiszam

Reputation: 187

If you open a ddd.txt with your application (the exe file), then the string[] Args will have two items: the program's path itself and the ddd.txt path. The following sample code shows you how you put your ddd.txt file in a textBox on Form1. Many thanks everyone for the help.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public static class Environment
        {
        }
        public Form1()
        {
            InitializeComponent();
        }

    private void Form1_Load(object sender, EventArgs e)
    {
        string[] args = System.Environment.GetCommandLineArgs();
        string filePath = args[0];
        for (int i = 0; i <= args.Length - 1; i++)
        {
            if (args[i].EndsWith(".exe") == false)
            {
                textBox1.Text = System.IO.File.ReadAllText(args[i],
                Encoding.Default);
            }
        }
    }
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        string[] args = System.Environment.GetCommandLineArgs();
        string filePath = args[0];
    }


}
public sealed class StartupEventArgs : EventArgs
{

}

}

Upvotes: 2

mveith
mveith

Reputation: 477

In Console application use args parameter in Main function. First arg is path to opening file.

For example:

class Program
{
    static void Main(string[] args)
    {
        var filePath = args[0];

        //...
    }
}

In WPF application use Application_Startup event:

private void Application_Startup(object sender, StartupEventArgs e)
{
    var filePath = e.Args[0];
    //...
}

Or use Enviroment class - anywhere in your .net application:

string[] args = Environment.GetCommandLineArgs();
string filePath = args[0];

Upvotes: 4

ΩmegaMan
ΩmegaMan

Reputation: 31576

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();            


// Set filter for file extension and default file extension 

dlg.DefaultExt = ".kkk"; 

dlg.Filter = "KKK documents (.kkk)|*.kkk"; 

Upvotes: 0

Related Questions