gpt4 book ai didi

C# 获取引用程序集中的相对路径

转载 作者:太空狗 更新时间:2023-10-29 21:54:10 26 4
gpt4 key购买 nike

我有 2 个项目 Project A , Project B ,项目 A 引用了项目 B ,项目 A 是一个可执行文件。

  Project A --> Project B 

在项目 B 中有一个名为“MyFolder”的目录

所以soulottion层次结构如下:

    MySolution 
- A
- B
- MyFolder

我如何从项目 A(可执行文件)中获取 MyFolder 的相对路径。

我找到了很多答案,其中陈述了以下内容:

  sring path = Assembly.GetAssembly(typeof(SomeClassInBProject)).Location;

我从这里得到的路径是 A 的 bin\debug 中 B.dll 的路径,我怎样才能在那个 .dll 中检索路径。

编辑:

我也试过:

        Assembly assembly = Assembly.GetAssembly(typeof(SomeClassInBProject));
FileStream fs = assembly.GetFile(@"MyFolder\myFile");

and

FileStream fs = assembly.GetFile("MyFolder\myFile");

and

FileStream fs = assembly.GetFile("myFile");

fs i 始终为 null。

最佳答案

Uri.MakeRelativeUri你在找什么?

string pathA = Assembly.GetExecutingAssembly().Location;
string pathB = Assembly.GetAssembly(typeof(SomeClassInBProject)).Location;

Uri pathAUri = new Uri(pathA);
Uri pathBUri = new Uri(pathB);

string relativePath = pathAUri.MakeRelativeUri(pathBUri).OriginalString;
string relativeMyFolder = Path.Combine(relativePath, "MyFolder");

更新

您可以使用 Assembly.GetFile()返回 FileStream 的方法。 FileStream 有一个 Name 属性,您可以在上面的代码中使用。

关于C# 获取引用程序集中的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21955109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com