c# 获取相对路径
2013-07-22 17:26
204 查看
本文修正了原文地址:
/article/9803451.html
的获取两个目录相对路径的方法的bug,在这里跟大家分享,欢迎指正。
/// <summary>
/// 获取路径2相对于路径1的相对路径
/// </summary>
/// <param name="strPath1">路径1</param>
/// <param name="strPath2">路径2</param>
/// <returns>返回路径2相对于路径1的路径</returns>
/// <example>
/// string strPath = GetRelativePath(@"C:/WINDOWS/system32", @"C:/WINDOWS/system/*.*" );
/// //strPath == @"../system/*.*"
/// </example>
public static string GetRelativePath(string strPath1, string strPath2)
{
if (!strPath1.EndsWith("\\")) strPath1 += "\\"; //如果不是以"/"结尾的加上"/"
int intIndex = -1, intPos = strPath1.IndexOf("\\");
///以"/"为分界比较从开始处到第一个"/"处对两个地址进行比较,如果相同则扩展到
///下一个"/"处;直到比较出不同或第一个地址的结尾.
while (intPos >= 0)
{
intPos++;
if (string.Compare(strPath1, 0, strPath2, 0, intPos, true) != 0) break;
intIndex = intPos;
intPos = strPath1.IndexOf("\\", intPos);
}
///如果从不是第一个"/"处开始有不同,则从最后一个发现有不同的"/"处开始将strPath2
///的后面部分付值给自己,在strPath1的同一个位置开始望后计算每有一个"/"则在strPath2
///的前面加上一个"../"(经过转义后就是"..//").
if (intIndex >= 0)
{
strPath2 = strPath2.Substring(intIndex);
intPos = strPath1.IndexOf("\\", intIndex);
while (intPos >= 0)
{
strPath2 = "..//" + strPath2;
intPos = strPath1.IndexOf("\\", intPos + 1);
}
}
//否则直接返回strPath2
return strPath2.Replace("\\","/");
}
/article/9803451.html
的获取两个目录相对路径的方法的bug,在这里跟大家分享,欢迎指正。
/// <summary>
/// 获取路径2相对于路径1的相对路径
/// </summary>
/// <param name="strPath1">路径1</param>
/// <param name="strPath2">路径2</param>
/// <returns>返回路径2相对于路径1的路径</returns>
/// <example>
/// string strPath = GetRelativePath(@"C:/WINDOWS/system32", @"C:/WINDOWS/system/*.*" );
/// //strPath == @"../system/*.*"
/// </example>
public static string GetRelativePath(string strPath1, string strPath2)
{
if (!strPath1.EndsWith("\\")) strPath1 += "\\"; //如果不是以"/"结尾的加上"/"
int intIndex = -1, intPos = strPath1.IndexOf("\\");
///以"/"为分界比较从开始处到第一个"/"处对两个地址进行比较,如果相同则扩展到
///下一个"/"处;直到比较出不同或第一个地址的结尾.
while (intPos >= 0)
{
intPos++;
if (string.Compare(strPath1, 0, strPath2, 0, intPos, true) != 0) break;
intIndex = intPos;
intPos = strPath1.IndexOf("\\", intPos);
}
///如果从不是第一个"/"处开始有不同,则从最后一个发现有不同的"/"处开始将strPath2
///的后面部分付值给自己,在strPath1的同一个位置开始望后计算每有一个"/"则在strPath2
///的前面加上一个"../"(经过转义后就是"..//").
if (intIndex >= 0)
{
strPath2 = strPath2.Substring(intIndex);
intPos = strPath1.IndexOf("\\", intIndex);
while (intPos >= 0)
{
strPath2 = "..//" + strPath2;
intPos = strPath1.IndexOf("\\", intPos + 1);
}
}
//否则直接返回strPath2
return strPath2.Replace("\\","/");
}
相关文章推荐
- C# ,asp.net 获取当前,相对,绝对路径
- C#获取相对路径的八种方法
- C#获取相对路径的几种方法
- C#获取文件相对路径
- 一个获取相对路径的方法(C#)
- C#获取相对路径的八种方法
- c# 获取相对路径
- C#获取相对路径的方法
- C#获取文件物理相对绝对路径目录的N种方法
- 一个获取相对路径的方法(C#)
- c# 获取相对路径
- C# ,asp.net 获取当前,相对,绝对路径
- C# ,asp.net 获取当前,相对,绝对路径
- C#获取相对路径
- c# 获取相对路径
- C# 获取相对路径的八种方法
- Winform 获取相对路径 C#
- C# 获取相对路径(绝对路径转相对路径)
- c# 获取相对路径
- (c#)获取相对路径