1

I run my program and it works fine. I am using external Batch and VBS files however if these files are not in my main C:\ Directory then it don't work at all! I get a cannot find file specified and so How can I make sure that my files run in my directory that my program installs in every time C:\Program Files (x86)\ then of course it makes a program folder.

screenshot

example of the code I used which I got from another forum on this site.

Process scriptProc = new Process();
            scriptProc.StartInfo.FileName = @"Services.bat";
            scriptProc.StartInfo.WorkingDirectory = @"c:\Program Files (x86)\Buzzard X Soy Optimzation Program\"; //<---very important 
            scriptProc.StartInfo.Arguments = "//B //Nologo Services.bat";
            scriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //prevent console window from popping up
            scriptProc.Start();
            scriptProc.WaitForExit();
            scriptProc.Close();
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Damian
  • 13
  • 1
  • 5
  • Are you running your code from `C:\>` directly? If so, then that is where `scriptProc.StartInfo.FileName` is looking, not other directories – OneCricketeer Oct 06 '21 at 23:17
  • no thats just for some reason where it works at – Damian Oct 06 '21 at 23:25
  • How are you running the code, though? From CMD? – OneCricketeer Oct 06 '21 at 23:27
  • Well Yes and No the buttons are compiled in VS but the Batch files runs through CMD yes. but for some reason it will only work if the files are directly in C: and C: only no sub folder I am also new to code and C#. – Damian Oct 06 '21 at 23:29

1 Answers1

1

You can use Environment.CurrentDirectory to get the directory from which your executeble was run, and navigate to the desired folder relative to your starting path.

You should virtually never put absolute paths in code, because of the exact problem you are encountering.

Nigel
  • 2,961
  • 1
  • 14
  • 32
  • can i get a example of this if you don't mind? and how I can a apply it? I am new to C# – Damian Oct 06 '21 at 23:26
  • @Buzzard Sure. I can show you how to do it with your code specifically if you give me some input. Directly above the code you wrote write this `var path = Environment.CurrentDirectory`. Put a breakpoint right after that and let me know what path is. – Nigel Oct 06 '21 at 23:33
  • I did that and do you want me to run it? – Damian Oct 06 '21 at 23:52
  • it seems to may have worked actually.. let me build it rq if it did work though thanks alot – Damian Oct 06 '21 at 23:55
  • @Buzzard youre welcome. If my answer solved the problem for you please upvote and select it as the best answer – Nigel Oct 07 '21 at 00:05