对文件C#执行OS命令
我试图通过C#执行操作系统命令。 我从这个网页上获得了以下代码:
//Execute command on file ProcessStartInfo procStart = new ProcessStartInfo(@"C:\Users\Me\Desktop\Test\System_Instructions.txt", "mkdir testDir"); //Redirects output procStart.RedirectStandardOutput = true; procStart.UseShellExecute = false; //No black window procStart.CreateNoWindow = true; //Creates a process System.Diagnostics.Process proc = new System.Diagnostics.Process(); //Set start info proc.StartInfo = procStart; //Start proc.Start();
但是当我尝试运行代码时,我收到以下错误:
{"The specified executable is not a valid application for this OS platform."}
我究竟做错了什么? 我也试过这个例子,但也遇到了同样的问题。
您正在使用的ProcessStartInfo
构造函数的重载需要一个可执行文件名和参数传递给它 – .txt
文件本身不可执行。
听起来更像是你想用文件中的命令执行批处理文件。 为此检查此SO线程: 如何使用ProcessStartInfo运行批处理文件?
您正在尝试执行TXT文件。 这就是你得到的原因
{“指定的可执行文件不是此OS平台的有效应用程序。”}
因为,指定的可执行文件(TXT)不是此OS平台的有效应用程序。
您将定位具有指定打开应用程序的可执行文件或其他文件。 您的目标是文本文件; 你应该做的是目标记事本,然后提供文本文件的路径作为参数:
ProcessStartInfo info = new ProcessStartInfo { FileName = "C:\\Windows\System32\\notepad.exe", Arguments = "C:\\Users\\Me\\Desktop\\Test\\System_Instructions.txt" } new Process.Start(info);
或者,如果您的文本文件要执行,则需要将其作为.bat文件。
尝试将USESHELLEXECUTE成员设置为TRUE而不是FALSE。
它对我有用 – 但我认为这会在发布后对某些用户进行重新调整。
您正在尝试执行此操作:
C:\Users\Me\Desktop\Test\System_Instructions.txt mkdir testDir
shell不知道如何“执行”文本文件,因此命令失败。
如果要将此文本文件作为批处理文件执行,请将文件扩展名更改为.bat
以便系统将其理解为批处理文件,然后设置UseShellExecute
以便对其执行默认操作(=运行它,如果是批处理文件)。
如果要在记事本中打开文件,请使用:
ProcessStartInfo procStart = new ProcessStartInfo("notepad.exe", @"C:\Users\Me\Desktop\Test\System_Instructions.txt");
如果要写入文件:
//In case the directory doesn't exist Directory.CreateDirectory(@"C:\Users\Me\Desktop\Test\); using (var file = File.CreateText(@"C:\Users\Me\Desktop\Test\System_Instructions.txt")) { file.WriteLine("mkdir testDir"); }
如果您要在文本文件中执行要执行的命令,只需将其重命名为.bat并且它应该可以工作(并且可能是内容使用“mkdir testDir”作为参数执行某些操作?)
你想达到什么目的? 创建一个目录? 使用“System.IO.Directory.CreateDirectory”方法。 打开带有相关程序的.txt文件? 使用ProcessStartInfo(@“。\ filename.txt”)并将UseShellExecute设置为true。 这将导致执行该文件类型的关联程序,这可能不是notepad.txt。