Own file extension - Double click does not handle over file path - c#

I've managed to create my own file extension following this tutorial: http://www.codeproject.com/Articles/17023/System-File-Association
So far, it works perfectly. I've got only one thing that I can't solve.
When I double-click on a file with that extension, my program opens up. Now, I'd want to perform an action in my program. I made my way through some threads here and read that the file path is automatically passed to the startup arguments.
The problem is that no single argument is passed, also Process.GetCurrentProcess().StartInfo.FileName returned an empty string. I think this is consecutively because I don't pass any arguments when double-clicking my file.
This is my code:
var fai = new FileAssociationInfo(".extension");
if (!fai.Exists)
{
try
{
fai.Create("My Extension Program");
var pai = new ProgramAssociationInfo(fai.ProgId);
if (!pai.Exists)
{
pai.Create("My Program File",
new ProgramVerb("Open", Application.ExecutablePath);
pai.DefaultIcon = new ProgramIcon(Application.ExecutablePath);
}
}
}
As you can see I only pass the application's path to open it up. But how can I pass the file path as argument now? I've seen that e.g. the author of the article passes "%1" as argument, I tried that, too, but nothing changed.
Thanks in advance.

ProcessStartInfo.FileName usually gives you the path to your program executable itself, not the file which was clicked in Windows Explorer, so this seems the wrong thing to check in your case.
If you want to get the arguments using the current Process, then Process.GetCurrentProcess().StartInfo.Arguments should give you a string containing all the arguments passed to the program. If there are multiple arguments, you would need to parse these into separate values yourself.
But the standard, simpler way to get the arguments is to make sure the Main() method of your program has signature static void Main(string[] args){}. args is already processed into separate values for you, so it is easier to handle it here, even if you only pass it off to another class or store them in a static variable.
The %1 should ensure the clicked file is passed as the first argument (args[0]) to your program.

Well, I got it. What I had to do was creating a subkey in ClassesRoot: "ProgramName\shell\open\command". Then set a value containing the application's path and attach "%1" to it and you're done.

Related

Write into a log file with C#

I am using the JitBit Macro Recorder to create "bots" that save me a lot of time at work. This program can use the mouse and the keyboard and perform tasks by checking different if-options like "if image found on screen".
My newest "bot" is about 900 lines of commands long and I would like to make a log-file to find an error somewhere in there. Sadly, this program doesn't offer such an option, but it let's me use c# as a task. I have NO experience with c# but I thought, that this is easy to do for someone who has some experience.
If I click execute c# code, I get the following input field:
Important: This code MUST contain a class named "Program" with a static method "Main"!
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
Now I need two code templates:
1. Write a message to a "bot_log.txt" located on my desktop.
[19.05.2016 - 12:21:09] "Checking if item with number 3 exists..."
The number "3" changes with every run and is an exact paste of the clipboard.
2. Add an empty line to the same file
(Everything should be added to a new line at the end of this file.)
If you have no idea how to program in C#, then you should learn it,
if you want to use code provided from answers.
And if you want to generate timestamps and stuff then it's not done within minutes and I don't think someone writes the whole code just for your fitting. Normally questions should have at least a bit of general interest.
Anyway:
This works, if you have a RichTextTbox in your program.
Just do a new event (like clicking a button) and do this inside it.
(This was posted somewhere here too or on another site, with sligh changes)
public static void SaveMyFile(RichTextBox rtb)
{
// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveLog = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the RTF extention for the file.
saveLog.DefaultExt = "*.rtf";
saveLog.Filter = "RTF Files|*.rtf"; //You can do other extensions here.
// Determine whether the user selected a file name from the saveFileDialog.
if (saveLog.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveLog.FileName.Length > 0)
{
// Save the contents of the RichTextBox into the file.
try
{
rtb.SaveFile(saveLog.FileName);
}
catch
{
MessageBox.Show("Error creating the file.\n Is the name correct and is enough free space on your disk\n ?");
}
MessageBox.Show("Logfile was saved successful.");
}
}

Could trying to copy a file owned by another process cause a DirectoryNotFoundException?

The log I'm trying to work with belongs to another program that runs concurrently with my own. I get a DirectoryNotFoundException stating "Could not find a part of the path " when I try to make the copy. The assert does pass. The exception is thrown at File.Copy(...) itself. With the if(File.Exists(...)) in place, the program is clearly able to see the file before it attempts to copy it.
Edit: Could permissions be a possible cause? The directory is located in the root of the C drive.
Edit: By adding the two asserts suggested by Jim Mischel and stepping through in the cold light of a new day, newControlProgramLog path was revealed as the culprit. GetSaveFilePath() was returning a default path for the particular run state I was testing. I declared the default but never checked to see that it existed on program start up. The directory is now created if it does not exist, and the function now works as intended.
Shout out to Christian Hagelid for calling that it wasn't an issue with controlProgramLogPath from the start.
private void CopyLogsToDataDirectoy()
{
Debug.Assert(Directory.Exists(_controlProgramDirectory));
string controlProgramLogPath = Path.Combine(_controlProgramDirectory, _controlProgramLogFileName);
if (File.Exists(controlProgramLogPath))
{
string dataFilePath = GetSaveFilePath();
string newControlProgramLogName = Path.GetFileNameWithoutExtension(dataFilePath);
newControlProgramLogName = newControlProgramLogName + ".control.log";
string newControlProgramLogPath = Path.GetDirectoryName(dataFilePath);
newControlProgramLogPath = Path.Combine(newControlProgramLogPath, newControlProgramLogName);
File.Copy(controlProgramLogPath, newControlProgramLogPath);
}
}
DirectoryNotFoundException occurs when part of the path you specified does not exist. It does not occur because a file is locked. If you get DirectoryNotFoundException, then it's almost certainly because the string you supplied does not reference a valid directory path. Documentation also says that you can get this exception if your code doesn't have the PathDiscovery permission. I suspect that's pretty unlikely in your case.
You should check the paths in controlProgramLogPath and newControlProgramLogPath immediately before calling File.Copy.
Debug.Assert(Directory.Exists(Path.GetDirectoryName(controlProgramLogPath));
Debug.Assert(Directory.Exists(Path.GetDirectoryName(newControlProgramLogPath));
I suspect that will reveal the problem.

How can I read the command line supplied to an offline clickonce application?

I have a simple application that opens a TCP connection and communicates via Telnet to another system. The application is to read a file that contains parameters and a simple scripting language to issue commands based on prompts from the connection.
Written in VS2013 using .NET 4
My application works as designed with one little exception.
I am publishing to a location using VS2013 which works well enough but the idea is to read a command line passed to my application that contains the path/file for the script to execute and that doesn't work as expected.
Finding out the hard way, the standard args[] parameters are not passed when it's published this way.
I have searched out multiple solutions that don't work both on here and other sites.
This is the basis (excerpt from page) of my current implementation to read the command line (found here: http://developingfor.net/2010/06/23/processing-command-line-arguments-in-an-offline-clickonce-application/). This seems to be similar to all solutions I've found, each with some variation that doesn't work.
string[] args = null;
if (ApplicationDeployment.IsNetworkDeployed)
{
var inputArgs = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;
if (inputArgs != null && inputArgs.Length > 0)
{
args = inputArgs[0].Split(new char[] { ',' });
}
}
else
{
args = e.Args;
}
This SHOULD return args[] with parameters passed. I believe it would also include the actual command with path to the application. The Split function is because the author wishes to pass arguments separated by commas and not spaces.
My incarnation of this is a bit longer to include some checks to see if we actually get arguments from being compiled as an exe instead. If I compile to EXE and supply a command line, all is fine. Here is my code, not very concise as I've made lots of changes to debug and make this work.
I haven't figured out how to debug in the ide as network deployed with a command line so my debug code is via messagebox.
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length == 0) //If we don't have args, assume onclick launch
{
if (ApplicationDeployment.IsNetworkDeployed) //are we oneclick launched?
{
var cmdline = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData; //this should hold the command line and arguments????
if (cmdline != null && cmdline.Length > 0) //we have something and it contains at least 1 value
{
//This is all debug code to see what we get since we can't trace in this mode
MessageBox.Show(cmdline.Length.ToString()); //how many objects do we have?
foreach (String s in cmdline)
{
MessageBox.Show(s); //show us the value of each object
}
Application.Run(new frmMain(args)); //launch the form with our arguments
}
else
{
//quit application
MessageBox.Show("No command line.1"); //debug so we know where we failed
Application.Exit();
}
}
else
{
//quit application
MessageBox.Show("No command line.2"); //debug so we know where we failed
Application.Exit();
}
}
else
{
Application.Run(new frmMain(args)); //launch form with args passed with exe command line
}
}
Running the code above like this:
sTelent.application 1234
I have also explored the URL passing method which seems to only apply if launched from a web server, which this application is not.
At first I got NULL for my object:
AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData
After more research I discovered that in my project properties under the Publish section there is an option button and under Manifests I can choose "Allow URL Parameters to be passed to application"
I checked this box and while I get different behavior, I don't get the desired behavior.
With that option checked I now get 2 messages boxes: The first showing the number of objects in cmdline and that number is 1 and the second showing the value of that one object which contains only the path/command to my application. No other objects and definitely not my arguments.
Am I totally off base? How do I get my command line arguments from an offline clickonce published application?
It seems that you must put the argument on the .appref-ms and not on not the .application or .exe for this to work correctly for clickonce based applications.
I created a short cut on my desktop by copying the installed application link found under All Programs. That should create an icon on your desktop with the same name as your application.
Then, open a command prompt, type in “%userprofile%\Desktop\My App Name.appref-ms” word for word (of course replace "my app name" with your application name). It should then pass the arguments. You can also put the command within a .bat file. I'm sure that you can also reference the link directly, it typically is located under c:\users[user profile]\appdata\roaming\Microsoft\windows\start menu\programs[app name]

winform application to launch and read from a file with custom extension

I am building a windows forms application using C# that needs to get launched when a user clicks on a file with custom extension(eg. filename.mycustomextension)
I plan to put a url in the filename.mycustomextension file. when user clicks on this file, we winform application should launch and also read contents of this file.
Is it possible to do this?
First and most obviously you'll need to associate the file extension with the application either by "open with" in the shell, through an installer or directly in the registry.
MSDN - Best Practices for File Associations
Then from there it's really pretty simple.
static class Program
{
[STAThread]
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
string text = File.ReadAllText(args[1]);
// ...
}
}
args[0] is the application path.
args[1] will be the file path.
args[n] will be any other arguments passed in.
Offhand I can't find any examples that show all of this together simply but Scott Hanselman has a nice example of loading files through a single instance WinForms application, about the same...
http://www.hanselman.com/blog/CommentView.aspx?guid=d2f676ea-025b-4fd6-ae79-80b04a34f24c
Yes, it is possible.
The idea is that when your application is clicked, you modify the registry key, to associate the extension file with your application.
Here are the sketches:
Use the FileAssociation class from here.
Initialize it, set all the parameters.
Here is an example:
var FA = new FileAssociation();
FA.Extension = "blah";
FA.ContentType = "application/blah";
FA.FullName = "blah Project File";
FA.ProperName = "blahFile";
FA.AddCommand("open", string.Format("\"{0}\" \"%1\"", System.Reflection.Assembly.GetExecutingAssembly().Location));
//"C:\\mydir\\myprog.exe %1");
FA.IconPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
FA.IconIndex = 0;
FA.Create();
If you plan to launch your application from a browser then there are security issues, but other than that - yes.
You just need to install the application on the user's machine and associate your .mycustomextension with the application. http://support.microsoft.com/kb/185453

Not able to pass text file(.txt) as command line argument to console application

I want to pass Text(.txt) file from command line arguments as a parameter to my console application.
This is a structure of my console application:
Now i want to pass SampleFile.txt file from command line argument which is in my project as you can see in image and print output of my txt file.
How to do this?
Can anybody tell me step by step procedure to do this as i am very much new to console application.
If you want to process "SampleFile.txt", when debugging your application, then:
right click on project in Solution Explorer, select "Properties";
switch to "Debug" page on the left;
type "SampleFile.txt" (with full path, if required), under "Start options/Command line arguments";
save project;
use args[0] to access file name you've passed.
When you right click on the project and go to Properties there should be a tab called Debug containing an option for setting command line arguments. There you can put the filename.
SampleFile.txt
The filename is then found in the args array when starting the application.
string fileName = args[0];
Copy your file always to output directory.
Add file path to command line arguments
Then you will get "SampleFile.txt" as a arg in your main method.
private static void Main(string[] args)
{
string yourFile = args[0];
}

Categories