我有两个项目和一个共享库,可从此文件夹加载图像: "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文件的位置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句