我有1個c#console appln,它使用Process.Start()方法執行任何腳本文件。我提供的腳本文件路徑爲Process1.StartInfo.FileName
。我的腳本文件可以是任何類型(.vbs,ps1等)。我也通過使用指令p.StartInfo.Arguments
將String傳遞給腳本。當執行腳本文件時,它應該將字符串重新回到c#應用程序。返回的字符串可以通過設置Process1.StartInfo.RedirectStandardOutput = true
來讀取,但是對於使用這條指令,我需要設置Process1.StartInfo.UseShellExecute = false
。 當我運行這個我得到錯誤爲「指定的可執行文件不是有效的Win32應用程序」。 我想這可能是因爲,當我設置Process1.StartInfo.UseShellExecute = false
時,我的appln不知道用哪個.exe來執行腳本文件。Process.StartInfo.UseShellExecute相關錯誤
另一方面,如果我提供的exe路徑StartInfo.FileName
和腳本文件路徑StartInfo.Argument
然後我沒有得到錯誤。 例如:我想執行PowerShell腳本,我設置以下屬性爲P1.StartInfo.FileName = "location of powershell.exe"
和p1.startInfo.Argument =".ps1 script file path"
,在這種情況下我沒有得到錯誤。
問題是我不提前知道哪種類型的腳本我要執行。也不能找出執行腳本文件在不同的不同的m/c上的.exe文件的位置。那麼是否有可能從相同的通用c#appln執行不同類型的腳本文件,並讀取腳本返回的輸出?
這裏是我的代碼
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Collections;
namespace process_csharp
{
class Program
{
static void Main(string[] args)
{
String path = null;
//this will read script file path
path = Console.ReadLine();
//this string is passed as argument to script
string s = "xyz";
Process p = new Process();
p.StartInfo.FileName= path;
p.StartInfo.Arguments = s;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.BeginOutputReadLine();
Console.WriteLine(p.StandardOutput.ReadToEnd());
}
}
}
:我想要傳遞字符串到腳本,我怎麼能這樣做? – sailer
只是追加你的字符串到'process.StartInfo。參數',編輯了代碼。 –
是的,工作感謝! – sailer