简体   繁体   English

无法从C#执行“ cmd”或批处理文件

[英]having trouble executing a “cmd” or batch file from c#

i need to run a batch file (or a cmd) from c# . 我需要从c#运行批处理文件(或cmd)。 my code is this simple: 我的代码很简单:

 Process.Start(@"C:\b.bat");
Process.Start(@"cmd.exe");

i have also tried Executing Batch File in C# , and many other sites but i do not think the problem is syntax related. 我也尝试过在C#和许多其他站点中执行批处理文件,但是我不认为问题与语法有关。

the error happens for either line above, which I have googled but not found a solution for my particular problem: 该错误发生在我搜索过但未找到针对我特定问题的解决方案的上述任一行上:

An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll Additional information: The specified executable is not a valid application for this OS platform. System.dll中发生了类型为'System.ComponentModel.Win32Exception'的未处理异常。其他信息:指定的可执行文件不是此OS平台的有效应用程序。

the weird thing is that these codes will run no problem: 奇怪的是,这些代码将不会出现问题:

Process.Start(@"IExplore.exe");
Process.Start("notepad");

i am running visual studio 2012 and compiling for x86, but my OS is windows 7 64-bit ,not sure if it matters.everything else in the program runs fine. 我正在运行Visual Studio 2012并针对x86进行编译,但是我的操作系统是Windows 7 64位,不确定是否重要。程序中的所有其他程序运行正常。

any help would be greatly appreciated! 任何帮助将不胜感激!

I think your problem is that you are trying to start an unknown process in Process.Start(@"C:\\b.bat") . 我认为您的问题是,您正在尝试在Process.Start(@"C:\\b.bat")启动未知进程。 When I do this i use the following. 当我这样做时,我将使用以下内容。

        string cmd = "/C b.bat";
        var m_command = new System.Diagnostics.Process();
        m_command.StartInfo.FileName = @"cmd.exe";
        m_command.StartInfo.Arguments = cmd;
        m_command.Start();

The /C will close the applciation after it is finished. / C将在完成后关闭应用程序。 So in essence the above code will: 因此,实质上,以上代码将:

  1. Start the cmd.exe process 启动cmd.exe进程
  2. Execute your arguments (in this case /C b.bat ) 执行参数(在本例中为/C b.bat
  3. You can also add m_command.WaitForExit() if you want to have the program wait for b.bat to finish executing before continuing. 如果希望程序在继续执行之前等待b.bat完成执行,则还可以添加m_command.WaitForExit()

Process.Start(@"C:\\b.bat"); ought to work, but putting it into the root may be causing the problem. 应该起作用,但是将其扎根可能会导致问题。 Try moving the bat file to your project directory, and put the absolute path to the file. 尝试将bat文件移动到您的项目目录,然后将绝对路径放入文件。 For example, I just had success with Process.Start(@"""C:\\dev\\ConsoleApplication1\\ConsoleApplication1\\test.bat"""); 例如,我刚刚在Process.Start(@"""C:\\dev\\ConsoleApplication1\\ConsoleApplication1\\test.bat""");

I solved the problem by running the 32 bit cmd with this command: 我通过使用以下命令运行32位cmd解决了该问题:

proc.StartInfo.FileName = @"C:\\windows\\system32\\cmd.exe"; proc.StartInfo.FileName = @“ C:\\ windows \\ system32 \\ cmd.exe”;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM