batch works fine but “windows cannot find devcon.exe” in c# program

这一生的挚爱 提交于 2020-01-16 12:03:15

问题


I have a batch file which disables and enables some driver using windows devcon. when I run this batch file by double-clicking on it it works fine. However, I tried to run it from a C# program that I wrote using this line:

System.Diagnostics.Process.Start("C:/*path to file*/file.bat");

it runs fine until it tries to open the devcon.exe and I get the following message:

after that it continues to run smoothly.

any ideas why it doesn't work from the C# program?

p.s I can't post the batch code due to IP issues...


回答1:


The problem is - as often - the "working directory". When you double-click something in the Explorer, the working directory is set to the current folder, so from the batch file's point of view it's current directory is its own directory.

When you execute a C# application, usually the working directory is the directory of the application's exe file, but not necessarily (for example if the application is run using a link, you can specify a different working directory). That's why, to find the application EXE file's directory it is not save to use GetCurrentDirectory.

So what happens is that the application runs the batch file, but with the application's directory, not the batch file's directory, as working directory. An alternative to an explicit cd within the batch file would be to specify the working directory when calling Process.Start.




回答2:


ok, after a little bit of research I found this simple solution: simply changing to the directory of the devcon.exe (using cd command) at the beginning of the batch code, i.e:

cd "C:/*path to the directory of devcon.exe*"
#rest of the code


来源:https://stackoverflow.com/questions/38990216/batch-works-fine-but-windows-cannot-find-devcon-exe-in-c-sharp-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!