我有一个控制台应用程序。在这个应用程序中,我创建了一个类libarary项目,我在主项目中引用了这个项目。在这个类库中,我有一个我想要得到的文件。这方面的代码:
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项目中运行良好。
为什么会发生这种情况?
编辑:
Directory.GetCurrentDirectory()
返回相同的路径。
发布于 2016-03-22 11:34:24
AppDomain.CurrentDomain.BaseDirectory
不是由程序集定义的,而是由宿主环境(即应用程序或服务)定义的。
构建控制台应用程序后,可执行程序集和辅助程序集将转到*.csproj
文件中定义的输出路径。默认值是bin\$(Configuration)
(例如:bin\Debug
)。
由于整个可执行文件都是在输出路径中执行的,所以这是基本目录。
为什么在ASP.NET WebAPI项目中在您的情况下工作得很好?可能是因为您在IIS中承载了ASP.NET WebAPI。如果您使用包含在Windows服务中的OWIN/Katana来执行此操作,则最终会出现相同的问题。
https://stackoverflow.com/questions/36153093
复制相似问题