unix系统中绝对路径转行成相对路径

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourcePath = "/u01/xib_local/wgq/";
            string targetPath = "/u01/xib_local/wgq/pgm/";

            System.Console.WriteLine("sourcePath:{0},targetPath:{1},relativePath:{2}", sourcePath, targetPath, GetRelativePath(sourcePath, targetPath));

            System.Console.ReadLine();

        }
        /// <summary>
        /// 获取相对路径,目标绝对路径相对源绝对路径的相对路径
        /// </summary>
        /// <param name="sourcePath">源绝对路径</param>
        /// <param name="targetPath">目标绝对路径</param>
        /// <returns>为空说明两者路径一致</returns>
        static string GetRelativePath(string sourcePath, string targetPath)
        {
            string relativePath = "";
            //获得数组
            string[] sourcePathArray = sourcePath.Split("/".ToCharArray());
            string[] targetPathArray = targetPath.Split("/".ToCharArray());
            //标志位初始值置为true
            bool isSame = true;
            //获取最大长度
            int maxLength = sourcePathArray.Length > targetPathArray.Length ? (sourcePathArray.Length - 1) : (targetPathArray.Length - 1);
            
            for (int i = 0; i < maxLength; i++)
            {
                if (i >= targetPathArray.Length - 1)
                {
                    //sourcePathArray长度较小
                    relativePath = "../" + relativePath;
                }
                else if(i >= sourcePathArray.Length - 1)
                {
                    //targetPathArray长度较小
                    relativePath = relativePath + targetPathArray[i] + "/";
                }
                else
                {
                    if (isSame && !sourcePathArray[i].Equals(targetPathArray[i]))
                    {
                        //isSave 从 true 变false
                        isSame = false;
                    }
                    if (!isSame)
                    {
                        //相对路径赋值
                        relativePath = "../" + relativePath + targetPathArray[i] + "/";
                    }
                    else
                    {
                        //否则继续循环
                        continue;
                    }
                }
            }
            return relativePath;
        }
    }
}

 

posted @ 2013-03-14 21:45  不扰凡尘  阅读(276)  评论(0编辑  收藏  举报