绝对路径转换为相对路径

时间:2022-03-03 20:35:36

最近写了个工作上要用到的工具,要和同事共用,需要储存各种文件路径,为了保证我们的文件结构相同,且减少文件错乱的问题,在储存文件路径的时候决定用相对路径来实现,就像VS里生成路径一样,随便把项目考到哪个地方都能保持正常运行。

但是网上一搜,悲催了,找了半天没有好到这方面的参考代码或思路什么的,所以自己想了一个傻瓜办法。

算法思路就是:举个列子,比如有参考路径:F:\\A\B\C\D\E

需要转换为相对路径的源路径:F:\\A\B\C-1\C-2\C-3\C-4

先找到两个路径共同的父路径strParent = F:\\A\B,然后把参考路径除了父路径外路径C\D\E转换为相对路径strRelative = ..\..\..\

然后把源路径的strParent替换为strRelative就可以了,很简单吧


下面是源码

        /// <summary>
/// 绝对路径转换为相对路径
/// </summary>
/// <param name="strReferencePath">参考路径</param>
/// <param name="strSourcePath">需要转换的路径</param>
/// <returns>返回转换后的路径</returns>
private string ChangeToRelativePath(string strReferencePath, string strSourcePath)
{
string strReferencePathRoot = Path.GetPathRoot(strReferencePath);
string strSourcePathRoot = Path.GetPathRoot(strSourcePath);

//不同盘符则不转换
if (strReferencePathRoot != strSourcePathRoot)
return strSourcePath;

//先清除末尾的‘\\’
strReferencePath = strReferencePath.TrimEnd('\\');
strSourcePath = strSourcePath.TrimEnd('\\');

string[] arrLocationDirSegment = strReferencePath.Split('\\');
string[] arrSourceDirSegment = strSourcePath.Split('\\');

if (arrLocationDirSegment.Length == 0 || arrSourceDirSegment.Length == 0)
return strSourcePath;

//参考路径和要转换的路径共同的父路径
string strSamePath = strReferencePathRoot;

//参考到父路径的相对路径
string strLocationRelativePath = string.Empty;

//以参考路径分段长度作为循环
for (int i = 1; i < arrLocationDirSegment.Length; i++)
{
if (i < arrSourceDirSegment.Length)
{
if (arrLocationDirSegment[i] == arrSourceDirSegment[i]) //若相同则为父路径
strSamePath += arrLocationDirSegment[i] + "\\";
else //若不同则为当前程序自己的路径,此路径就需要转换为相对路径
strLocationRelativePath += "..\\";
}
else//若需要转换的路径长度小于当前程序路径,此路径就需要转换为相对路径
strLocationRelativePath += "..\\";
}

return strSourcePath.Replace(strSamePath, strLocationRelativePath);
}
小弟第一次写博客,有点小兴奋呢,如果大家有更好的想法可以提出来,大家互相交流学习