如何从Windows任务计划程序调用时获取可执行文件所在目录?
解决方案:获取可执行文件的实际目录而非当前工作目录
问题的核心在于Directory.GetCurrentDirectory()和Environment.CurrentDirectory返回的是当前工作目录,该目录由启动程序的父进程(任务计划的taskeng.exe/taskmgr.exe)决定,而非你的控制台EXE所在路径。要在EXE同目录创建日志,需直接获取可执行文件的路径并提取其目录。
针对VB.NET 4.7.2,推荐以下两种可靠方法:
方法1:获取启动程序集(EXE)的路径
适用于DLL模块需要获取主EXE目录的场景(即使DLL与EXE不在同一目录):
Imports System.Reflection Imports System.IO ' 获取主EXE的所在目录 Dim exeDirectory As String = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
方法2:获取应用程序域的基目录
这是更简洁的方式,通常直接指向主EXE的目录:
Imports System.IO ' 获取应用程序基目录(即EXE所在目录) Dim exeDirectory As String = AppDomain.CurrentDomain.BaseDirectory
完整日志写入示例(WriteLog模块中)
Imports System.IO Imports System.Reflection Public Sub WriteLog(message As String) ' 选择上述任意一种方法获取目录 Dim exeDirectory As String = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) ' 或者用:Dim exeDirectory As String = AppDomain.CurrentDomain.BaseDirectory ' 构造日志文件夹路径 Dim logFolderPath As String = Path.Combine(exeDirectory, "Logs") ' 确保日志文件夹存在 If Not Directory.Exists(logFolderPath) Then Directory.CreateDirectory(logFolderPath) End If ' 构造日志文件路径(按日期命名) Dim logFileName As String = $"Log_{DateTime.Now.ToString("yyyyMMdd")}.log" Dim logFilePath As String = Path.Combine(logFolderPath, logFileName) ' 写入日志(追加模式) File.AppendAllText(logFilePath, $"[{DateTime.Now:HH:mm:ss}] {message}{Environment.NewLine}") End Sub
关键说明
Assembly.GetEntryAssembly():返回启动当前应用程序的程序集(即你的控制台EXE),无论代码在DLL还是EXE中,都能准确获取主程序的路径。AppDomain.CurrentDomain.BaseDirectory:返回当前应用程序域的基目录,默认就是主EXE的所在目录,无需引用System.Reflection命名空间。- 两种方法均不受父进程工作目录影响,在任务计划程序调用时能稳定获取EXE的实际路径。
内容的提问来源于stack exchange,提问作者Matthew Carr
相关产品推荐
相关产品推荐

