Sometimes runs .exe from the current folder

I have an application that launches an executable file that is in the same folder as this application, doing:

Process procStarter = new Process(); procStarter.StartInfo.FileName = "OtherApp.exe"; procStart.Start(); 

which works fine until I used an open file or file save dialog in my application. Then it cannot find the OtherApp.exe file.

This is normal? Can I just fix this by adding the current folder to StartInfo.Filename (and how to get the current folder)?

+4
source share
6 answers

Using the file dialog box probably changes the current directory of your process. To access the file in the same folder as the current executable, you can use the following code:

 string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); path = Path.Combine(path, "OtherApp.exe"); 
+10
source

Or you can add to your code:

 saveFileDialog1.RestoreDirectory = true ; 

when asking for file names.

+3
source

The problem is that you can change the current working directory when performing other file operations.

You want to remember the path, as other posters showed, but maybe you want to create your own instance of ProcessStartInfo and use ProcessStartInfo.WorkingDirectory so that you can remember the correct path.

+1
source

Try to explicitly specify the path to the OtherApp.exe file.

In the open file dialog, you can change the current directory.

0
source

If you do not specify the folder explicitly, the system will search the process in the current working directory.

The current working directory (usually) starts as the exe directory of the application, but can be changed by viewing it using the Open or Save dialog box.

Using an explicit file path is the correct answer. The best way is to not rely on the working directory at all, but use the path to the file of the current executable file as a base.

Here are some ways to do this: Application.StartupPath , Application.ExecutablePath

The code might look something like this:

 var exeName = "sample.exe"; var exePath = Path.Combine( Path.GetDirectoryName( Application.ExecutablePath ), exeName); 
0
source

Try System.IO.Path.Combine( System.Windows.Forms.Application.StartupPath, "myfile.exe" );

If this is not the best winforms project divo answer (imo, during this answer)

0
source

Source: https://habr.com/ru/post/1303744/


All Articles