C#獲取程式執行路徑的幾種方法
通過控制檯程式打印出每種方法的結果
static void Main(string[] args) { Console.WriteLine("typeof(Program).Assembly.Location:\r\n{0}", typeof(Program).Assembly.Location); Console.WriteLine(""); Console.WriteLine("Process.GetCurrentProcess().MainModule.FileName:\r\n{0}", Process.GetCurrentProcess().MainModule.FileName); Console.WriteLine(""); Console.WriteLine("Environment.CurrentDirectory:\r\n{0}", Environment.CurrentDirectory); Console.WriteLine(""); Console.WriteLine("AppDomain.CurrentDomain.BaseDirectory:\r\n{0}", AppDomain.CurrentDomain.BaseDirectory); Console.WriteLine(""); Console.WriteLine("AppDomain.CurrentDomain.SetupInformation.ApplicationBase:\r\n{0}", AppDomain.CurrentDomain.SetupInformation.ApplicationBase); Console.WriteLine(""); Console.Read(); }
通過另一個程式啟動的程式碼
static void Main(string[] args) { String path = "..\\..\\..\\TestExecutePath\\bin\\Debug\\TestExecutePath.exe"; Console.WriteLine("準備啟動:"+path); try { Process.Start(path); Console.WriteLine("啟動成功"); } catch(Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); }
通過其他程式啟動的執行結果:
typeof(Program).Assembly.Location:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug\TestExecutePath.exe
Process.GetCurrentProcess().MainModule.FileName:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug\TestExecutePath.exe
Environment.CurrentDirectory:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath.Startup\bin\Debug
AppDomain.CurrentDomain.BaseDirectory:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug\
AppDomain.CurrentDomain.SetupInformation.ApplicationBase:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug\
直接執行結果:(注意不是通過點選除錯執行)
typeof(Program).Assembly.Location:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug\TestExecutePath.exe
Process.GetCurrentProcess().MainModule.FileName:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug\TestExecutePath.exe
Environment.CurrentDirectory:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug
AppDomain.CurrentDomain.BaseDirectory:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug\
AppDomain.CurrentDomain.SetupInformation.ApplicationBase:
C:\Users\Administrator\Documents\Visual Studio 2015\Projects\TestExecutePath\Tes
tExecutePath\bin\Debug\