c# exe 路径

Application.StartupPath——获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。  
   
  Environment.CurrentDirectory——获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。  
   
  Application.ExecutablePath——获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
 
 通过调用Process.GetCurrentProcess().MainModule.FileName可获得当前执行的exe的文件名。

 AppDomain.CurrentDomain.SetupInformation.ApplicationBase获取当前应用程序所在的路径。

  1、Application.ExecutablePath  
  2、Application.StartupPath  
  3、Application.UserAppDataRegistry.ToString()  
  4、System.Environment.CurrentDirectory.ToString()  
  5、Directory.GetCurrentDirectory()  
  6、AppDomain.CurrentDomain.BaseDirectory  
  


string   GetAppPath()  
  {  
  string   FileName=System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;  
  FileName=FileName.Substring   (   0,FileName.LastIndexOf("//"));  
  return   FileName;  
  } 

### C# 获取当前可执行文件的完整路径方法 在 C# 中,获取当前可执行文件的完整路径有多种方式。以下是几种常用的方法及其代码示例: #### 方法一:使用 `Assembly.GetExecutingAssembly().Location` 此方法通过反射获取当前正在执行的程序集的完整路径,包括文件名。 ```csharp using System; using System.Reflection; class Program { static void Main() { string executablePath = Assembly.GetExecutingAssembly().Location; Console.WriteLine("可执行文件路径: " + executablePath); } } ``` 这种方法适用于大多数场景,但需要注意的是,如果程序被打包或嵌套到其他程序集中(例如某些压缩工具生成的单文件应用程序),返回的路径可能不准确[^1]。 #### 方法二:使用 `Application.ExecutablePath` `Application.ExecutablePath` 是 Windows 窗体应用程序中常用的方法,用于直接获取当前可执行文件的完整路径。 ```csharp using System; using System.Windows.Forms; class Program { static void Main() { string executablePath = Application.ExeciblePath; Console.WriteLine("可执行文件路径: " + executablePath); } } ``` 此方法简单直观,但在控制台应用程序中不可用,因为 `Application` 类属于 `System.Windows.Forms` 命名空间[^4]。 #### 方法三:使用 `Type.Assembly.Location` 通过类型信息获取当前程序集的位置。 ```csharp using System; class Program { static void Main() { string executablePath = typeof(Program).Assembly.Location; Console.WriteLine("可执行文件路径: " + executablePath); } } ``` 这种方法与 `Assembly.GetExecutingAssembly().Location` 类似,但更灵活,可以用于获取特定类型的程序集路径[^3]。 #### 方法四:使用 `System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName` 通过进程信息获取当前可执行文件的完整路径。 ```csharp using System; using System.Diagnostics; class Program { static void Main() { string executablePath = Process.GetCurrentProcess().MainModule.FileName; Console.WriteLine("可执行文件路径: " + executablePath); } } ``` 此方法直接从操作系统层面获取当前进程的主模块路径,通常更加可靠[^5]。 ### 注意事项 - 如果需要获取可执行文件所在的目录路径,可以结合 `Path.GetDirectoryName` 方法使用。例如: ```csharp using System; using System.IO; using System.Reflection; class Program { static void Main() { string executablePath = Assembly.GetExecutingAssembly().Location; string directoryPath = Path.GetDirectoryName(executablePath); Console.WriteLine("可执行文件目录: " + directoryPath); } } ``` - 在某些特殊情况下(如单文件部署或影子复制),上述方法可能返回非预期的结果。因此,在实际开发中需根据具体需求选择合适的方法[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值