简体   繁体   中英

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

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?

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

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 .

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, ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM