Command line with parameters

2019-08-22 16:11发布

问题:

i have this code:

string filePath = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH") + fileName;
string newFilePath = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH") + fileName.Replace(".dbf", ".csv");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH");
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format("\"{0}\" \"{1}\" /EXPORT:{2} /SEPTAB", ConfigurationManager.AppSettings.Get("DBF_VIEWER_PATH"), filePath, newFilePath);
try
{
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
}
catch{}

The problem is, that it starts command line, and does nothing. It seems that it does not pass arguments to command line (command line is empty). Anybody has an idea where the problem could be?

回答1:

I resolved my problem. It was in me. I was trying to launch command line and give parameters to it, so it would launch another program with parameters. Isn't that stupid? Now i launch the program i need with parameters and it works perfectly:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH");
startInfo.FileName = ConfigurationManager.AppSettings.Get("DBF_VIEWER_PATH");
startInfo.Arguments = string.Format("\"{0}\" /EXPORT:{1} /SEPTAB", filePath, newFilePath);
using (Process exeProcess = Process.Start(startInfo))
{
    exeProcess.WaitForExit();
}


回答2:

You could try to add /c (Carries out command and then terminates) argument to cmd.exe:

startInfo.Arguments = string.Format("/c \"{0}\" \"{1}\" /EXPORT:{2} /SEPTAB", ConfigurationManager.AppSettings.Get("DBF_VIEWER_PATH"), filePath, newFilePath);

EDIT: As Pedro noted, you really should avoid catch{} as it will hide any thrown exception.



回答3:

Use catch like this:

try
{
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
}
catch(Exception ex)
{
     Console.Writeline(ex.ToString());
     Console.ReadKey();
}

so the occured exception will be displayed and will give you crucial informations about what is wrong.