c# 执行命令行并返回字符串
我无法让它返回任何内容,我期待当前目录中的文件列表,但它什么也没返回。
class Program
{
static void Main(string[] args)
{
PublishProject();
Console.ReadLine();
}
public static void PublishProject()
{
//Create process
var pProcess = new System.Diagnostics.Process
{
StartInfo =
{
FileName = "cmd.exe",
Arguments = "dir",
UseShellExecute = false,
RedirectStandardOutput = true,
WorkingDirectory = "C:\\"
}
};
pProcess.Start();
Console.Write(pProcess.StandardOutput.ReadToEnd());
pProcess.Close();
Console.WriteLine("done");
}
}
I can't get this to return anything, I'm expecting a list of files in the current directory but it's returning nothing.
class Program
{
static void Main(string[] args)
{
PublishProject();
Console.ReadLine();
}
public static void PublishProject()
{
//Create process
var pProcess = new System.Diagnostics.Process
{
StartInfo =
{
FileName = "cmd.exe",
Arguments = "dir",
UseShellExecute = false,
RedirectStandardOutput = true,
WorkingDirectory = "C:\\"
}
};
pProcess.Start();
Console.Write(pProcess.StandardOutput.ReadToEnd());
pProcess.Close();
Console.WriteLine("done");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过将
Arguments
更改为:/C Flag “执行字符串指定的命令,然后停止。”。如果没有这个,cmd 仍在执行,这就是为什么你不会立即得到输出。
话虽这么说,对于这个例子,我个人会使用 Directory.GetFiles或 Directory.EnumerateFiles 而不是进程。
You can make this work by changing
Arguments
to:The /C Flag "Carries out the command specified by string and then stops.". Without this, cmd is still executing, which is why you get no output immediately.
That being said, for this example, I would personally use Directory.GetFiles or Directory.EnumerateFiles instead of a process.
如果您想列出目录中的文件,最好的方法是使用 System.IO 中的 Directory 类,如下所示:
*注意,这不是完整的工作源代码,因为它不包含
main()
函数。If you want to list down the files in the directory, the best way is to use the
Directory
class fromSystem.IO
as follows:*note that this is not a full working source code because it doesn't contain the
main()
function.