在文件c#上执行操作系统命令

本文关键字:操作 系统命令 执行 文件 | 更新日期: 2023-09-27 18:05:16

我正在尝试通过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."}

我做错了什么?我也试过这个例子,但也遇到了同样的问题。

在文件c#上执行操作系统命令

您正在使用的ProcessStartInfo构造函数的过载期望一个可执行的文件名和参数传递给它- .txt文件本身是不可执行的。

听起来更像是要在文件中执行带有命令的批处理文件。检查这个SO线程:我如何使用ProcessStartInfo来运行批处理文件?

尝试将USESHELLEXECUTE成员设置为TRUE而不是FALSE。

这对我来说很有效,但我认为这在发布后会对某些用户产生负面影响。

您正在尝试执行一个TXT文件。这就是为什么你得到

{"指定的可执行文件不是此操作系统平台的有效应用程序。"}

因为指定的可执行文件(TXT)不是这个操作系统平台的有效应用程序

您可以针对具有指定打开应用程序的可执行文件或其他文件。你的目标是一个文本文件;您应该做的是瞄准记事本,然后将文本文件的路径作为参数提供:

ProcessStartInfo info = new ProcessStartInfo
{
    FileName = "C:''Windows'System32''notepad.exe",
    Arguments = "C:''Users''Me''Desktop''Test''System_Instructions.txt"
}
new Process.Start(info);

或者,如果您的意思是要执行文本文件,则需要将其创建为.bat文件。

你正在尝试执行这个:

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。