Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Open With -problem-
I have a ".txt" file renamed with a custom extension: ".bzx".
I want this file, when I click on it, to be able to: "Open With" MyCustomProgram from "\Program Files\or\whatever".
How do I copy the content of that file into a variable from MyCustomProgram using StreamReader method(or OtherMethod) ?

StreamReader reader = new StreamReader(path + "\\?????!!!!??????.txt")


....after some time I discover the terms to ask this question properly (I hope the terms are right)...
let me rephrase:
How do I pass a random file to the Load method as a parameter?
That is all the time I wanted to ask... im not very friendly with terms.
Posted
Updated 6-Sep-11 22:40pm
v9
Comments
Sergey Alexandrovich Kryukov 5-Sep-11 13:49pm    
Language?
--SA
_Q12_ 5-Sep-11 13:51pm    
c#
Dr.Walt Fair, PE 5-Sep-11 14:15pm    
Your question isn't very clear. Do you want to configure Windows to open the file with your application? Or are you trying to do something inside your application?
_Q12_ 5-Sep-11 14:25pm    
I am trying to do something inside my application! A little more specific: How do I open a file located in c:\a.txt , another one in c:\Program Files\IIS\Microsoft Web Deploy\ redist.txt , another one in c:\Users\Public\Documents\Demos\Components\Forms\Xt\CS\BarTutorials\AddBarItemLinks\AddBarItemLinks.txt without placing specific path [new StreamReader(path + "\\?.?")] for name and extension, but just referring to MyProgram to open it?
_Q12_ 5-Sep-11 16:44pm    
so?


One way is to pass it as a string:
C#
public void Load(string path)
{
    using(StreamReader reader = new StreamReader(path))
    {
        // do whatever you need to do with the file
    }
}


[EDIT]
Okay, you want to be able to double click a file and have it open in your program? Well, it sounds like you got the file extension registered to your program, so:

1. In Program.cs add a string array as a parameter to your Main(). This will contain the path to the file you double clicked on.
C#
static void Main ( string[] args )
{
    if ( args.Length > 0 )
    {
        Application.Run( new MainFrm( args[0].Trim() ) );
    }
    else
    {
        Application.Run( new MainFrm() );
    }
}


2. Overload your program's main form constructor to take a string. This is how you will pass the path from the program's entry point to the form.
C#
public partial class MainForm : Form
{
    private string file_path = string.Empty;

    public MainForm (){}
    public MainForm ( string path )
    {
        this.file_path = path;
    }
}


3. Use the file_path variable to open the file, I would write a separate LoadFile() function that can be called from either the MainForm_Load event handler or anywhere else in your code you might want to load a file from.
C#
public partial class MainForm : Form
{
    private string file_path = string.Empty;

    public MainForm (){}
    public MainForm ( string path )
    {
        this.file_path = path;
    }

    private void MainForm_Load ( object sender, EventArgs e )
    {
        if ( this.file_path != string.Empty )
        {
            this.LoadFile();
        }
    }

    private void LoadFile()
    {
        using ( StreamReader reader = new StreamReader ( new FileStream ( this.file_path, FileMode.Open ) ) )
        {
            // do whatever you need to do to load into your program here
        }
    }
}

[/EDIT]
 
Share this answer
 
v2
Comments
_Q12_ 7-Sep-11 4:34am    
STILL NOT WORKING:
string path = Application.StartupPath;
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "";
//string pathCustom = Convert.ToString(sender); //not working
//using (StreamReader reader = new StreamReader(sender.ToString())) //not working
using (StreamReader reader = new StreamReader(path)) //not working
{
string line;
while ((line = reader.ReadLine()) != null)
{
//list.Add(line); // Add to list.
label1.Text += line + "\r";
}
}
}

So, When I double click on the file, MyCustomProgram open but it cant read anything from the file(in label1).
JOAT-MON 7-Sep-11 5:42am    
This is not a Load function, it is the event handler for the OnLoad event. It gets called after the form instantiates, but before it displays. It is intended for setting properties and values on your form and its controls before drawing them. See my updated answer for help on what I think you are trying to do.
_Q12_ 15-Sep-11 17:34pm    
I did not see the "Program.cs" part... Its working wonderfully.
Thanks!!! You got a 5stars from me + accepted solution.
I did registered the file extension with my program in the classical way (windows way-"Open With" dialog).
I have added this code (with some great help from another place) to be able to properly register the file extension - I expose it here just for the COMPLETED solution:
here is my code:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
private string file_path = string.Empty;
public Form1(string[] args)
{
InitializeComponent();
label1.Text = "";
//Added this requirement so we can detect the file that is calling the executable
if (args.Length != 0)
{
file_path = args[0];
}
else
{
label1.Text = "------Select a [.testingarea] file to be open with this program------";
}
}


private void Form1_Load(object sender, EventArgs e)
{
SetAssociation(".testingarea", "FileTypeExtensionAssociation File", Application.ExecutablePath, "Testingarea File");

using (StreamReader reader = new StreamReader(file_path))
{
label1.Text = reader.ReadToEnd();
reader.Close();
}
}


public static void SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription)
{
RegistryKey BaseKey;
RegistryKey OpenMethod;
RegistryKey Shell;
RegistryKey CurrentUser;

BaseKey = Registry.ClassesRoot.CreateSubKey(Extension);
BaseKey.SetValue("", KeyName);

OpenMethod = Registry.ClassesRoot.CreateSubKey(KeyName);
OpenMethod.SetValue("", FileDescription);
OpenMethod.CreateSubKey("DefaultIcon").SetValue("", "\"" + OpenWith + "\",0");
Shell = OpenMethod.CreateSubKey("Shell");
Shell.CreateSubKey("edit").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
Shell.CreateSubKey("open").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\"");
BaseKey.Close();
OpenMethod.Close();
Shell.Close();


// Delete the key instead of trying to change it
CurrentUser = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.testingarea", true);
CurrentUser.DeleteSubKey("UserChoice", false);
CurrentUser.Close();

// Tell explorer the file association has been changed
SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
}

[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);


}
}

+

static class Program //in Program.cs
{
///
/// The main entry point for the application.
/// /// added string[] args to catch file calling the executing assembly
///

[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));

}
}
C#
string txt = File.ReadAllText(path + "filename.ext");
 
Share this answer
 
Comments
_Q12_ 5-Sep-11 13:01pm    
filename.ext can take any form! :)
form= any name and any extension imaginable.
Mehdi Gholam 5-Sep-11 13:10pm    
Yes, you can load any text file from the above line.
_Q12_ 5-Sep-11 13:12pm    
how do I open a file located in c:\a.txt , another one in c:\Program Files\IIS\Microsoft Web Deploy\ redist.txt , another one in c:\Users\Public\Documents\Demos\Components\Forms\Xt\CS\BarTutorials\AddBarItemLinks\AddBarItemLinks.txt without placing specific path, name and extension, but just referring to MyProgram to open it?
Mehdi Gholam 5-Sep-11 13:21pm    
What do you mean by MyProgram?
_Q12_ 5-Sep-11 16:45pm    
MyProgram = the code compiled in .exe form (from c#). MyProgram usage = I want to have it put somewhere from I can refer to it (like Program Files). Its not an installed program, its just a copy.
The question and many comments are not clear... but anyway, that answer should give some directions:

1) To associate an extention with a particular program, the easiest way is through a setup project...

It is generally not a good idea to simply copy the file as it won't appear in Add/Remove program, the file might get blocked after the download, it won't create a shorthcut in the menu or on the desktop...

2) To build a path, you use Path class. The most useful method is Combine:
Path.Combine[^]

One advatange of using such function is that you don't have to check if the directory ends with a / or a \ before combining parts.

3) To get the name of predefined folder, you use:
Environment.GetFolderPath[^]

Typically, an application would use some subdirectories of those predefined folders

4) You can get the path of the executable from executing assembly and its properties:
Assembly.GetExecutingAssembly[^]

It is not recommanded to use that folder or any subfolder of Program files for user data as that folder is "protected" in Windows Vista and Windows 7. User data should generally be under "My documents" or under user application data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900