[英]system() to c# without calling cmd.exe
如何在不調用 cmd.exe 的情況下將 system("") 轉換為 C#? 編輯:我需要拋出“dir”之類的東西
如果我正確理解了您的問題,那么您正在尋找Process.Start 。
請參閱此示例(來自文檔):
// Opens urls and .html documents using Internet Explorer.
void OpenWithArguments()
{
// url's are not considered documents. They can only be opened
// by passing them as arguments.
Process.Start("IExplore.exe", "www.northwindtraders.com");
// Start a Web page using a browser associated with .html and .asp files.
Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");
Process.Start("IExplore.exe", "C:\\myPath\\myFile.asp");
}
編輯
正如您所說,您需要諸如“dir”命令之類的東西,我建議您查看DirectoryInfo 。 您可以使用它來創建自己的目錄列表。 例如(也來自文檔):
// Create a DirectoryInfo of the directory of the files to enumerate.
DirectoryInfo DirInfo = new DirectoryInfo(@"\\archives1\library");
DateTime StartOf2009 = new DateTime(2009, 01, 01);
// LINQ query for all files created before 2009.
var files = from f in DirInfo.EnumerateFiles()
where DirInfo.CreationTimeUtc < StartOf2009
select f;
// Show results.
foreach (var f in files)
{
Console.WriteLine("{0}", f.Name);
}
正如其他人所指出的,它是Process.Start 。 例子:
using System.Diagnostics;
// ...
Process.Start(@"C:\myapp\foo.exe");
不知道我是否理解你的問題。 您在尋找Process.Start
嗎?
I need to throw something like "dir"
如果你需要運行 DIR,那么你需要調用 cmd.exe 因為 dir 是 cmd.exe 的內部
你真的想要等價物嗎? 您可能並不依賴於您究竟要做什么。
例如,從命令行調用copy
本身就有一個 C# 等效項File.Copy
,對於dir
有一個用於獲取信息的整個Directory
類(這些是數千個示例中的一個快速示例)。 根據您的需求,C# 很可能為您嘗試運行的特定命令提供了一個庫/函數,通常也是一個更強大的方法,而不是全局處理程序。
如果全局“調用這個”是你所追求的,那么正如其他答案所暗示的那樣,使用System.Diagnostics.Process
類是你最好的選擇。
如果要執行命令行 (cmd.exe) 命令,例如“dir”或“time”或“mkdir”,請將命令作為參數傳遞給 cmd.exe 並帶有標志 /C。
例如,
cmd.exe /C dir
或者
cmd.exe /C mkdir "New Dir"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.