Reputation: 2479
I want a new instance of my app to be created for every filepath handed to it via command-line args at startup.
Right now I have this in my main window's constructor:
if (args.Length > 0)
{
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
if (File.Exists(arg))
{
if (i > 0)
Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location, arg);
else
OpenFile(arg);
}
}
}
But, right now my program seems to create new instances of itself until my computer runs our of memory. Do you see what's wrong?
--Edit--
The Args come from an override of the Appplication.OnStartup Event.
Upvotes: 0
Views: 108
Reputation: 2479
Answer: I'm an idiot.
For testing purposes I hard-coded some args, which ever new instance then spawned with.
Feel free to point and laugh or throw eggs at me through your computer screen.
Upvotes: 1
Reputation: 887459
Change it to
Process.Start(typeof(MainWindow).Assembly.Location, "\"" + arg + "\"");
(With quotes around the argument)
If arg came from a quoted path with spaces, passing it to Process.Start
will pass the unquoted value as two arguments. You need to put quotes around it to ensure that you only get one argument.
Changing the first parameter will make it shorter and a little faster, but won't vchange the behavior.
Upvotes: 1
Reputation: 59111
Remove the check for if (args.Length > 0)
, because the for-loop will take care of that. If you need to skip arg 0 (as suggested by SLaks), just change the for-loop to int i = 1
.
Note that if you always pass an argument to a sub-process, and your check is based on their being any arguments, you will infinitely recurse.
So this line should change:
if (i > 0)
// Spawn new process, passing the argument
To:
if (i > 1)
// Spawn new process, passing the argument
Also, this code is fairly confusing, as has been proven by the answers here. Here is much simpler code:
foreach (string arg in args.Skip(2)) // Just Skip(1) if it turns out args[0] != this.exe
Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location, arg);
if (args.Length > 1) // > 0 if it turns out args[0] != this.exe
OpenFile(args[1]);
Upvotes: 3
Reputation: 169018
If your goal is to allow all of the processing to run concurrently, why not just use threads?
foreach (var i in args) {
new Thread(delegate {
try { OpenFile(i); }
catch (Exception e) { Console.WriteLine("Error processing file {0}: {1}",
i, e.ToString()); }
}).Start();
}
Upvotes: 0