-4

I want to run an exe file with c# but I can't use Process.Start() because I don't know the exe file's location.

I didn't start to writing so I don't have any code for now.

jps
  • 20,041
  • 15
  • 75
  • 79
Demir
  • 13
  • 5
  • "*because I don't now the exe file's direction.*" -- what does "direction" mean here? `Process.Start` is **the** way to run an exe from from C# – canton7 Dec 24 '20 at 11:32
  • I meant "location", the path of the exe file – Demir Dec 24 '20 at 11:35
  • You want to run a file, but you dont know where the file is? How do you even know the file exists? This cannot be done, obviously. – Camilo Terevinto Dec 24 '20 at 11:36
  • 1
    If the file exists in your PATH, just provide the exe name to `Proess.Start`, and it will search your PATH to find the exe. – canton7 Dec 24 '20 at 11:37
  • Did you know, at least, the name of exe? If it's a running process, you can find it [manually](https://www.raymond.cc/blog/determine-program-path-from-task-manager-for-each-program-in-windows-xp-windows-server-2003/) ([shell](https://superuser.com/questions/768984/show-exe-file-path-of-running-processes-on-the-command-line-in-windows)) – Nodtem66 Dec 24 '20 at 11:43

1 Answers1

0

Use following :

            string locateFile = "cmd.exe";
            string environPath = Environment.GetEnvironmentVariable("Path");
            string[] paths = environPath.Split(new char[] { ';' }).ToArray();

            string filePath = "";
            foreach (string path in paths)
            {
                string file = Directory.GetFiles(path, locateFile, SearchOption.TopDirectoryOnly).FirstOrDefault();
                if (file != null)
                {
                    filePath = file;
                    break;
                }
            }
            if (filePath.Length > 0)
            {
                Console.WriteLine("File location : '{0}'", filePath);
            }
            else
            {
                Console.WriteLine("File not found");
            }
            Console.ReadLine();
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • No need to go to these lengths, surely? `Process.Start` already searches `PATH` – canton7 Dec 24 '20 at 11:46
  • @canton7 : The process class has no Environmental variables. And if you set the Process Path variable and the file is not found then you have to handle the exception. – jdweng Dec 24 '20 at 11:47
  • Not sure what you're trying to say I'm afraid. `Process.Start("cmd.exe")` works fine, for example. Yes you will get an exception if the exe doesn't exist in your PATH, but that's fine – canton7 Dec 24 '20 at 11:51
  • @canton7 : I've never use that overload before. Every case when I use the process class I get an exception and the fix is to add the full path. – jdweng Dec 24 '20 at 11:58
  • You get exactly the same if you [use `ProcessStartInfo`](https://dotnetfiddle.net/flqCOo) – canton7 Dec 24 '20 at 12:00