C#相对路径转绝对路径,绝对路径转相对路径

 

1.绝对路径转相对路径

 

绝对转相对似乎C#没有提供实现,需要自己写,这里摘选了一位博友的实现方法:

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();
        }
RelativePath

 

调用:

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();
}

 

 

2.相对路径转绝对路径

 

可以直接用.Net自己的Path.GetFullPath转换。用SetCurrentDirectory改变当前比较路径

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

转载于:https://www.cnblogs.com/hont/p/5412340.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值