Catch Commandline error
I am trying to catch an error with an incorrect commandline parameter for the application of form
Myapp.exe myFile.txt
The application however throws an "Unhandled exception - The path is not of legal form".
Below is my code and I am wondering why it does not show the message box as provided in the code? Thanks.
String[] cmdlineArgs = Environment.GetCommandLineArgs();
if (cmdlineArgs.Length == 2)
{
try
{
if (File.Exists(cmdlineArgs[1].ToString()))
ConfigPar开发者_开发技巧ameters.SetConfigParameters(cmdlineArgs[1].ToString());
else
{
MessageBox.Show("Configuration file does not exist.Restarting...");
Environment.Exit(1);
}
}
catch (Exception ex)
{
}
If you pass an invalid path to File.Exists
(such, C:\D:/E:\
), you get that exception.
Check for improper characters in the file path (e.g. '>' <'>, etc...).
http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx & http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars.aspx
You should modify your code like bellow is more better :D
String[] cmdlineArgs = Environment.GetCommandLineArgs(); if (cmdlineArgs.Length == 2) { try { if (File.Exists(cmdlineArgs[1].ToString())) ConfigParameters.SetConfigParameters(cmdlineArgs[1].ToString()); } catch (Exception ex) { MessageBox.Show("Configuration file does not exist.Restarting..."); Environment.Exit(1); } }
Because when your file path contain some special characters(<, >, ?, *, etc), the File.Exists() maybe throw exception as you see.
精彩评论