C#应用程序无法正确执行批处理文件命令
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在装有 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.
从 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.