路径(path)的分隔符:unix和linux中为/(正斜杠),windows中为\(反斜杠),相对路径两者都可以

相对路径解析:

1).\system32\.exe 一个 .表示当前目录(相对路径以当前在编辑的文档为出发点)

2)..\表示父目录

3)../../表示根目录

 

相对路径转绝对路径的实现:RelativePath

string RelativePath(string absolutePath, string relativeTo)
        {
            //from - www.cnphp6.com

            string[] absoluteDirectories = absolutePath.Split('\\');
            string[] relativeDirectories = relativeTo.Split('\\');

            //Get the shortest of the two paths
            int length = absoluteDirectories.Length < relativeDirectories.Length ? absoluteDirectories.Length : relativeDirectories.Length;

            //Use to determine where in the loop we exited
            int lastCommonRoot = -1;
            int index;

            //Find common root
            for (index = 0; index < length; index++)
                if (absoluteDirectories[index] == relativeDirectories[index])
                    lastCommonRoot = index;
                else
                    break;

            //If we didn't find a common prefix then throw
            if (lastCommonRoot == -1)
                throw new ArgumentException("Paths do not have a common base");

            //Build up the relative path
            StringBuilder relativePath = new StringBuilder();

            //Add on the ..
            for (index = lastCommonRoot + 1; index < absoluteDirectories.Length; index++)
                if (absoluteDirectories[index].Length > 0)
                    relativePath.Append("..\\");

            //Add on the folders
            for (index = lastCommonRoot + 1; index < relativeDirectories.Length - 1; index++)
                relativePath.Append(relativeDirectories[index] + "\\");
            relativePath.Append(relativeDirectories[relativeDirectories.Length - 1]);

            return relativePath.ToString();
        }

 

调用转换方法:

static void Main(string[] args)
{
    var path = RelativePath(@"D:\MyProj\Release", @"D:\MyProj\Log\MyFile.txt");

    Console.WriteLine(path);//print ..\Log\MyFile.txt
    Console.Read();
}

相对路径转绝对路径:

注意用SetCurrentDirectory改变当前比较路径

static void Main(string[] args)
{
    var relativePath = @"..\..\Release";
    //Directory.SetCurrentDirectory(...)
    Console.WriteLine(Path.GetFullPath(relativePath));
    Console.Read();
}

注意:

相对路径在使用前,一般需要通过Path.GetFullPath()转换为绝对路径。

 

Logo

更多推荐