如何从两个不同的项目中获取文件夹的相对性

我有两个项目和一个共享库,从该文件夹加载图像: "C:/MainProject/Project1/Images/"

Project1的文件夹: "C:/MainProject/Project1/Files/Bin/x86/Debug" (其中有project1.exe)

Project2的文件夹: "C:/MainProject/Project2/Bin/x86/Debug" (其中有project2.exe)

当我调用共享库函数来加载图像时,我需要获取“Images”文件夹的相对路径,因为我将从project1或project2调用该函数。 此外,我将我的MainProject移动到其他计算机,所以我不能使用绝对路径。

从Project1我会做:

 Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + @"\Images"; 

从Project2我会做:

 Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName + @"Project1\Images"; 

如何通过两个项目文件夹获取相对路径?

您可能希望稍微测试一下此代码并使其更加健壮,但只要您不传递UNC地址,它就应该可以工作。 它的工作原理是将路径分成目录名并从左到右进行比较。 然后建立相对路径。

  public static string GetRelativePath(string sourcePath, string targetPath) { if (!Path.IsPathRooted(sourcePath)) throw new ArgumentException("Path must be absolute", "sourcePath"); if (!Path.IsPathRooted(targetPath)) throw new ArgumentException("Path must be absolute", "targetPath"); string[] sourceParts = sourcePath.Split(Path.DirectorySeparatorChar); string[] targetParts = targetPath.Split(Path.DirectorySeparatorChar); int n; for (n = 0; n < Math.Min(sourceParts.Length, targetParts.Length); n++ ) { if (!string.Equals(sourceParts[n], targetParts[n], StringComparison.CurrentCultureIgnoreCase)) { break; } } if (n == 0) throw new ApplicationException("Files must be on the same volume"); string relativePath = new string('.', sourceParts.Length - n).Replace(".", ".." + Path.DirectorySeparatorChar); if (n <= targetParts.Length) { relativePath += string.Join(Path.DirectorySeparatorChar.ToString(), targetParts.Skip(n).ToArray()); } return string.IsNullOrWhiteSpace(relativePath) ? "." : relativePath; } 

而不是使用Directory.GetCurrentDirectory,请考虑使用Path.GetDirectory(Process.GetCurrentProcess()。MainModule.FileName)。 您当前的目录可能与您的exe文件不同,这会破坏您的代码。 MainModule.FileName直接指向exe文件的位置。

我的建议是保持exes所在的共享(图像)目录。 换句话说,项目的安装文件夹。 现在找到安装目录,使用以下代码: –

  var imageFolderName = "SharedImage"; var loc = System.Reflection.Assembly.GetExecutingAssembly().Location; var imagePath = Path.Combine(loc, imageFolderName);