[英]How to get Current Project Directory path using C#
好的,这是问题。 我有两个项目,一个是 C# 控制台,另一个是类库。 我正在从控制台应用程序访问/调用类库方法。 类库项目中有一个名为 Files 的文件夹。
我需要获取类库文件文件夹的路径,但每当我使用
System.IO.Directory.GetCurrentDirectory();
和
Environment.CurrentDirectory;
它为我提供了我用来调用该方法的控制台项目的路径。
以上方法给了我类似的路径
C:\\ConsolePro\\bin\\Debug
但我需要类库项目的路径
C:\\ClassLibPro\\bin\\Debug
请指教
一旦代码编译并运行,“项目路径”就没有意义了。 您所能确定的只是已编译程序集的文件位置。 如果您的控制台项目直接引用构建的“类库”DLL,而不是通过项目引用,您只能执行您所要求的操作。
然后,您可以使用 Reflection 来获取 Assembly 路径,例如;
string path = Assembly.GetAssembly(typeof (SomeClassInOtherProject)).Location;
您应该能够多次使用Directory.GetParent(Directory.GetCurrentDirectory())
来获取更高级别的目录,然后将 lib 目录的路径添加到该目录的末尾。
我认为问题是:
由于控制台项目具有 DLL 文件引用,因此它使用 DLL 来调用任何方法。 此时它返回位于控制台项目的 bin 目录中的类库项目的 DLL 位置,它不知道类库项目的物理位置。
所以本质上它返回相同的项目路径。 为了解决这个问题,我将不得不将两个项目移动到同一个目录中。
如果您从另一个程序集加载类库。
string Path = System.Reflection.Assembly.GetAssembly(typeof({LibraryClassName})).Location;
string PathToClassLibPro = Path.GetDirectoryName( Path);
将{LibraryClassName}
替换为您的库的类名。
我希望我正确地理解你:
Path.GetDirectoryName(typeof(Foo.MyFooClass).Assembly.Location);
我会推荐两个选项之一。
如果文件很小,则将它们包含在类库中,并在需要时将它们流式传输到临时位置
另一种选择是在构建过程中将文件复制到输出目录并以这种方式使用它们。 在多个共享项目的情况下,最好有一个公共的 bin 文件夹,您可以将程序集复制到该位置并从该位置运行。
尽管我找不到一个好的解决方案,但我还是使用了这个技巧:只要你想回到你的理想路径,你就应该添加Directory.GetParent()而不是......
Directory.GetParent(...(Directory.GetParent(Directory.GetCurrentDirectory()).ToString()...).ToString()
我使用以下方法在运行时获取当前项目路径:
public static class ProjectInfo {
public static string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
public static string projectPath = appDirectory.Substring(0, appDirectory.IndexOf("\\bin"));
}
我也有这个确切的问题,我无法访问命名空间的 bin/debug 文件夹中的文件。 我的解决方案是使用Split()
操作字符串,然后构造一个新字符串,它是我在命名空间中的 json 文件的绝对路径。
private static string GetFilePath()
{
const char Escape = '\\'; //can't have '\' by itself, it'll throw the "Newline in constant" error
string directory = Environment.CurrentDirectory;
string[] pathOccurences = directory.Split(Escape);
string pathToReturn = pathOccurences[0] + Escape; //prevents index out of bounds in upcoming loop
for(int i = 1; i < pathOccurences.Length; i++)
{
if (pathOccurences[i] != pathOccurences[i - 1]) //the project file name and the namespace file name are the same
pathToReturn += pathOccurences[i] + Escape;
else
pathToReturn += typeof(thisClass).Namespace + Escape; //In the one occurrence of the duplicate substring, I replace it with my class Namespace name
}
return pathToReturn + "yourFile.json";
}
我个人不喜欢这个解决方案,但这是我能想到的唯一答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.