8

I am writing a c# app that needs to be able to be ran from a usb, and it launches other programs that are installed to the usb. Not necessarily the computer it's being ran on. I am launching these applications by doing:

Process.Start("notmyprogram.exe");

this works great however I am finding that this only works if notmyprogram.exe. is installed to the computers hard drive. If I want to run a program not installed on the computer, but rather to the usb, I have to call it directly, like so:

Process.Start("D:\\Programs\\notmyprogram\\applicationinstalledonusb.exe");

Where D: is the letter assigned by my OS. However, obviously the drive letter changes per computer, it wont always be D. MY application is located on the usb so my question is: is there any way to find what drive letter my exe is ran from so I could then append the directory to the end of the drive letter? Or maybe I'm simply going about it the wrong way and there's a more efficient way to accomplish this?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Halter
  • 48
  • 2
  • 6
  • 30
  • @AlexeiLevenkov I've been searching this for the last day, SO is usually my last resort as I find I learn better if I figure it out myself. If this has already been answered then I apologize, but I could not find it. – Halter Jan 10 '14 at 18:46
  • 1
    possible duplicate of [How to get files in a relative path in C#](http://stackoverflow.com/questions/3259583/how-to-get-files-in-a-relative-path-in-c-sharp) – Thomas Weller Jan 10 '14 at 18:47
  • I think this should be what you are looking for: http://msdn.microsoft.com/en-us/library/system.appdomain.basedirectory(v=vs.110).aspx – mao47 Jan 10 '14 at 18:47
  • Side note: Here is search query that gives you results - not sure what you used that did not find anything: http://stackoverflow.com/search?q=[c%23]+relative+executable – Alexei Levenkov Jan 10 '14 at 18:49

2 Answers2

12

Try this (using System.IO):

string root = Path.GetPathRoot(System.Reflection.Assembly.GetEntryAssembly().Location);

Also, You can use Path.GetFullPath() instead Path.GetPathRoot() and remove unwanted part from the string without hardcoding the folder name

Kaf
  • 33,101
  • 7
  • 58
  • 78
  • 1
    That worked! just have to add the directory to the root now, thanks! – Halter Jan 10 '14 at 19:06
  • @nope No need to rebuild the full path. Get the current directory through `Path.GetDirectoryName(Path.GetFullPath(...))` then use [Path.Combine](http://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx) to navigate from there. – nmclean Jan 10 '14 at 19:54
0

I use to split crurrent directory string and get first element, like the following:

Directory.GetCurrentDirectory().Split('\\')[0]
tiebob
  • 96
  • 6