Click here to Skip to main content
15,905,322 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Lets say, I've wrote with WPF some simple text editing program like NotePad.

When I open any ".txt" file with command "Open with" (my editor) how do I get path of this file from my program?

Thanks in advance.
Posted
Updated 16-Apr-12 18:49pm
v2

It depends on the command line written in the file type registration. Most typically, the first parameter is used and the file with input document. You get its name using the method System.Environment.GetCommandLineArgs()[1], please see:
http://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs.aspx[^].

It's important to check up the number of command line arguments checking the length of the array returned by the function shown above — the command line may not have parameters. In all cases, the very first parameter is always a file name of a main executable module of the entry assembly of the running application.

Another method is using the parameters passed to the entry point of the application; normally, this is the Main method. Please see:
http://en.wikipedia.org/wiki/Main_function#C.23[^].

For this purpose, you should use the signature with args and use args[0] (first parameter is the first parameter in the command line, not executable file name). You should always check up if the length of the array is more than zero; zero is the case of empty command line.

For a sophisticated yes easy-to-use command line setup and parsing, please see my article on the topic:
Enumeration-based Command Line Utility[^].

—SA
 
Share this answer
 
Comments
VJ Reddy 17-Apr-12 1:24am    
Comprehensive answer. 5!
Sergey Alexandrovich Kryukov 17-Apr-12 11:11am    
Thank you, VJ.
--SA
C#
// Create OpenFileDialog

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

 

// Set filter for file extension and default file extension

dlg.DefaultExt = ".txt";

dlg.Filter = "Text documents (.txt)|*.txt";

 

// Display OpenFileDialog by calling ShowDialog method

Nullable<bool> result = dlg.ShowDialog();

 

// Get the selected file name and display in a TextBox

if (result == true)

{

    // Open document

    string filename = dlg.FileName;

    FileNameTextBox.Text = filename;

 }
</bool>



Source: OpenFileDialog in WPF[^]
 
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