C#-取exe文件绝对路径

 方法一(加入dll):

using System.Runtime.InteropServices;
#region
/// <summary> /// 取exe文件绝对路径 /// </summary> /// <param name="hModule"></param> /// <param name="lpFileName"></param> /// <param name="nSize"></param> /// <returns></returns> [DllImport("kernel32")] public static extern int GetModuleFileName(IntPtr hModule, [Out] StringBuilder lpFileName,int nSize); #endregion
#region
IntPtr processHandle = IntPtr.Zero;
StringBuilder exeFileNamestrB = new StringBuilder(260);
GetModuleFileName(processHandle, exeFileNamestrB, exeFileNamestrB.Capacity);
#endregion

方法二:(推荐-exe等)

System.Environment.CurrentDirectory  // 获取或设置当前工作目录的完全限定路径,使用System.Environment.CurrentDirectory只能得到运行的虚拟路径,得不到物理路径

方法三:其他定时任务运行时请用:

System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

方法四:(推荐-WCF,WebServer等)

System.Web.Hosting.HostingEnvironment  // 

例:WebServer使用外部文件时:

static readonly string strCon = System.Web.Hosting.HostingEnvironment.MapPath($"/bin") + @"/data.db";
//C:\\Users\\PC1\\source\\repos\\SqliteWebApp\\SqliteWebApp\\bin/data.db

方法五:(NET6 WebAPI)

string a = AppDomain.CurrentDomain.BaseDirectory;  // 运行文件目录
string c = Environment.ProcessPath;  // 可能是runtime目录

方案六:(推荐)

string fileName = Application.StartupPath+@"\Popup.bmp";

posted @ 2020-11-20 16:04  ꧁执笔小白꧂  阅读(312)  评论(0)    收藏  举报