2011-08-09 84 views
1

我试图通过C#执行OS命令。我从this webpage采取了以下代码:在文件C上执行OS命令#

//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."}

我在做什么错?我试过this example as well,但得到了同样的问题。

+0

您尝试执行文本文件,该文件(错误指示)不可执行。如果你想创建一个文件夹,我建议使用System.IO类,例如DirectoryInfo,Fileinfo等。 –

+0

从描述中完全不清楚你试图完成什么。 – MarkPflug

回答

4

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

听起来更像是你想用文件内的命令执行批处理文件。为了检查这个线程:How do I use ProcessStartInfo to run a batch file?

+0

这很有道理。那么我会如何去处理非.exe文件呢? –

+2

@Peppered你想要做什么“这个”?你想在记事本中打开文件吗?你想写入“mkdir testDir”到该文件中吗?你只是想执行“mkdir testDir”而没有任何文本文件?你想执行文本文件中的语句吗? – Davy8

+0

我想取一堆文件,保存它们(已经完成了这部分),然后对它们执行一些命令(我不知道它会是什么)。我也不知道我会得到什么类型的文件 –

2

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

{"The specified executable is not a valid application for this OS platform."}

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

1

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

ProcessStartInfo info = new ProcessStartInfo 
{ 
    FileName = "C:\\Windows\System32\\notepad.exe", 
    Arguments = "C:\\Users\\Me\\Desktop\\Test\\System_Instructions.txt" 
} 

new Process.Start(info); 

另外,如果你的意思是你的文本文件来执行,它需要进行一个.bat文件。

0

您正试图执行此:

C:\Users\Me\Desktop\Test\System_Instructions.txt mkdir testDir 

shell有没有线索,因此命令失败如何“执行”的文本文件。

如果你想执行这个文本文件作为一个批处理文件,以.bat使系统明白这是一个批处理文件,然后设置UseShellExecute因此它为它的默认操作(=运行时,它改变文件扩展名,在批处理文件的情况下)。

0

如果你想打开记事本文件,使用:

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”作为参数进行操作?)

0

你想完成什么? 创建一个目录?使用“System.IO.Directory.CreateDirectory”方法。 用相关程序打开一个.txt文件?使用ProcessStartInfo(@“。\ filename.txt”)并将UseShellExecute设置为true。这将导致执行该文件类型的关联程序,该程序可能不是notepad.txt。

+0

我想拿一堆文件,保存它们(已经完成了这个部分),然后对它们执行一些命令(我不知道它会是什么)。我也不知道我将拥有什么类型的文件 –

1

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

它适用于我 - 但我认为这对发布后的某些用户有影响。

+0

我的不好 - 这是对问题答案发布的链接的答案......如果你关注我。 – else

0

检查当前用户是否有权读写执行,如果不是明确更改用户或权限。