我有一个控制台应用程序。在此应用程序中,我创建了一个类库项目,我在主项目中引用了该项目。在这个类库中,我有一个我想要获取的文件。代码:
public static string GetPath(string fileName)
{
char separator = Path.DirectorySeparatorChar;
string startupPath = AppDomain.CurrentDomain.BaseDirectory;
string[] pathItems = startupPath.Split(separator);
string projectPath = string.Join(separator.ToString(),
pathItems.Take(pathItems.Length - 1)) + ".Handler";
string path = Path.Combine(projectPath, "WebRequestHandlers\\Files" + separator + fileName);
return path;
}
我之前在 .net web 项目中使用过它并且它有效,但由于某种原因这是我的 AppDomain.CurrentDomain.BaseDirectory:
C:\projects\OverWatchServerCall\OverWatchServerCall\bin\Debug\
应该是:
C:\projects\OverWatchServerCall\OverWatchServerCall\
该文件位于类库项目中,正如我之前所说,它在 .net web api 项目中运行良好
为什么会发生这种情况?
编辑:
Directory.GetCurrentDirectory()
返回相同的路径
最佳答案
AppDomain.CurrentDomain.BaseDirectory
不是由程序集定义的,而是由托管环境(即应用程序或服务)定义的。
构建控制台应用程序后,您的可执行文件和附属程序集将转到 *.csproj
文件中定义的输出路径。默认为 bin\$(Configuration)
(例如:bin\Debug
)。
由于整个可执行文件在输出路径中执行,因此这是基目录。
为什么 ASP.NET WebAPI 项目在您的案例中运行良好?可能是因为您在 IIS 中托管 ASP.NET WebAPI。如果您使用 Windows 服务中托管的 OWIN/Katana 来执行此操作,您最终会遇到相同的问题。
关于c# - 为什么 AppDomain.CurrentDomain.BaseDirectory 的目标是控制台应用程序中的 bincatelog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36153093/