摘自:依依杂菜馆

**//// <summary>
获取路径2相对于路径1的相对路径
/// 获取路径2相对于路径1的相对路径
获取路径2相对于路径1的相对路径
/// </summary>
获取路径2相对于路径1的相对路径
/// <param name="strPath1">路径1</param>
获取路径2相对于路径1的相对路径
/// <param name="strPath2">路径2</param>
获取路径2相对于路径1的相对路径
/// <returns>返回路径2相对于路径1的路径</returns>
获取路径2相对于路径1的相对路径
/// <example>
获取路径2相对于路径1的相对路径
/// string strPath = GetRelativePath(@"C:\WINDOWS\system32", @"C:\WINDOWS\system\*.*" );
获取路径2相对于路径1的相对路径
/// //strPath == @"..\system\*.*"
获取路径2相对于路径1的相对路径
/// </example>

获取路径2相对于路径1的相对路径public static string GetRelativePath(string strPath1, string strPath2)
获取路径2相对于路径1的相对路径获取路径2相对于路径1的相对路径
获取路径2相对于路径1的相对路径{
获取路径2相对于路径1的相对路径    
if (!strPath1.EndsWith("\\" )) strPath1 += "\\";    //如果不是以"\"结尾的加上"\"
获取路径2相对于路径1的相对路径    
int intIndex = -1, intPos = strPath1.IndexOf('\\');
       
///以"\"为分界比较从开始处到第一个"\"处对两个地址进行比较,如果相同则扩展到
       ///下一个"\"处;直到比较出不同或第一个地址的结尾.

获取路径2相对于路径1的相对路径    
while(intPos >= 0)
获取路径2相对于路径1的相对路径获取路径2相对于路径1的相对路径    
获取路径2相对于路径1的相对路径{
获取路径2相对于路径1的相对路径        intPos 
++;
获取路径2相对于路径1的相对路径        
if (string.Compare(strPath1, 0, strPath2, 0, intPos, true!= 0break;
获取路径2相对于路径1的相对路径        intIndex 
= intPos;
获取路径2相对于路径1的相对路径        intPos 
= strPath1.IndexOf('\\', intPos);
获取路径2相对于路径1的相对路径    }

获取路径2相对于路径1的相对路径
       ///如果从不是第一个"\"处开始有不同,则从最后一个发现有不同的"\"处开始将strPath2
       ///的后面部分付值给自己,在strPath1的同一个位置开始望后计算每有一个"\"则在strPath2

       ///的前面加上一个"..\"(经过转义后就是"..\\").
获取路径2相对于路径1的相对路径    
if (intIndex >= 0)
获取路径2相对于路径1的相对路径获取路径2相对于路径1的相对路径    
获取路径2相对于路径1的相对路径{
获取路径2相对于路径1的相对路径        strPath2 
= strPath2.Substring(intIndex);
获取路径2相对于路径1的相对路径        intPos 
= strPath1.IndexOf("\\", intIndex);
获取路径2相对于路径1的相对路径        
while(intPos >= 0)
获取路径2相对于路径1的相对路径获取路径2相对于路径1的相对路径        
获取路径2相对于路径1的相对路径{
获取路径2相对于路径1的相对路径            strPath2 
= "..\\" + strPath2;
获取路径2相对于路径1的相对路径            intPos 
= strPath1.IndexOf("\\", intPos + 1);
获取路径2相对于路径1的相对路径        }

获取路径2相对于路径1的相对路径    }
       //否则直接返回strPath2
获取路径2相对于路径1的相对路径    
return strPath2;
获取路径2相对于路径1的相对路径}


相关文章:

  • 2022-12-23
  • 2022-01-09
  • 2022-02-03
  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-07
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
  • 2022-01-03
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案