方法一(加入dll):

using System.Runtime.InteropServices;
  • 1.
#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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
#region
IntPtr processHandle = IntPtr.Zero;
StringBuilder exeFileNamestrB = new StringBuilder(260);
GetModuleFileName(processHandle, exeFileNamestrB, exeFileNamestrB.Capacity);
#endregion
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

方法二:(推荐-exe等)

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

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

System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
  • 1.

方法四:(推荐-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
  • 1.
  • 2.

方法五:(NET6 WebAPI)

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

方案六:(推荐)

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

作者:꧁执笔小白꧂