2014-02-26 99 views
1

我有两个项目,并从该文件夹中的图像加载一个共享库得到一个文件夹的相对: "C:/MainProject/Project1/Images/"如何从两个不同的项目

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

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

当我调用共享库函数来加载图像,我需要取得的“图片”文件夹中的相对路径,因为我会打电话从功能project1或project2。另外我会将我的MainProject移动到其他计算机上,所以我不能使用绝对路径。

从PROJECT1我会做:

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

从Project2的,我会做:

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

我怎样才能获得两个工程文件夹中的相对路径?

回答

2

您可能想要稍微测试一下这段代码,并使其更加健壮,但只要您不传递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的,(Process.GetCurrentProcess()。MainModule.FileName)考虑使用Path.GetDirectory。你的当前目录可能与你的exe文件不同,这会破坏你的代码。 MainModule.FileName直接指向你的exe文件的位置。

0

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

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