C#应用程序无法正确执行批处理文件命令

发布于 2024-10-20 11:48:32 字数 737 浏览 1 评论 0原文

public void runBatchfile(String batchfilename)
{
   try
   {
      ProcessStartInfo processInfo = new ProcessStartInfo(batchfilename);
      processInfo.UseShellExecute = false;
      Process batchProcess = new Process();
      batchProcess.StartInfo = processInfo;
      batchProcess.StartInfo.CreateNoWindow = true;
      batchProcess.Start();
      batchProcess.WaitForExit();
   }
   catch (Exception r) { }
}

runBatchfile(@"c:\lol.bat");

lol.bat 包含这两行

dir c:\ /s /b > c:\filelist.txt
exit

,当我运行代码时,它所做的只是创建一个 filelist.txt 文件,但实际上并不执行命令的其余部分,如果我手动将其插入到 CMD 中,它确实有效。

顺便说一句,我尝试过扩展名 .cmd,并且也尝试过不使用 exit 命令,但没有任何其他结果。

请帮我 :)

public void runBatchfile(String batchfilename)
{
   try
   {
      ProcessStartInfo processInfo = new ProcessStartInfo(batchfilename);
      processInfo.UseShellExecute = false;
      Process batchProcess = new Process();
      batchProcess.StartInfo = processInfo;
      batchProcess.StartInfo.CreateNoWindow = true;
      batchProcess.Start();
      batchProcess.WaitForExit();
   }
   catch (Exception r) { }
}

runBatchfile(@"c:\lol.bat");

lol.bat contains these 2 lines

dir c:\ /s /b > c:\filelist.txt
exit

and when I run my code all it does is creating a filelist.txt file, but doesn't actually perform the rest of the command, which does work if I manually insert it into CMD.

Btw I've tried making the extension .cmd and I also tried without the exit command, without any other results.

please help me :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

筱武穆 2024-10-27 11:48:32

在装有 Visual Studio 2010 的 Windows 7 64 位计算机上,直接从 IDE 运行此代码不会执行任何操作。

预感这可能与写入驱动器 C: 根目录的权限有关,我尝试使用管理员权限直接从资源管理器窗口运行 .exe(右键单击,以管理员身份运行),结果成功了。

我想说这是一个权限问题。

也许您可以将输出重定向到位于其他位置的文件?

更新

我更改了批处理文件,以便 dir 命令重定向到我的桌面并且运行得很好。

On my Windows 7 64-bit machine with Visual Studio 2010, running this code straight from the IDE doesn't do anything whatsoever.

On a hunch that it might have something to do with permission to write to the root directory of drive C:, I tried running the .exe directly from an Explorer window with admin rights (right-click, Run as Administrator) and that worked.

I'd say it's a permission problem.

Maybe you could redirect the output to a file located elsewhere?

update:

I changed the batch file so that the dir command gets redirected to my desktop and it runs just fine.

梦亿 2024-10-27 11:48:32

从 C# 调用时我也遇到过这个问题。我通常使用的解决方法是在运行命令时物理地允许它显示窗口。不知道为什么这会产生影响,但它过去对我有用。

I've had issues with this as well when calling from C#. The workaround that I usually use is to physically allow it to show the window when running the command. Not sure why this makes a difference but it has worked for me in the past.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文