C# 中获取项目的相对路径

绝对路径:
D://ora//YSQSXT_HY//HYQS_Client_DKH//DKHBOBIAO//大客户运费结算日报(一).cll
相对路径:
../../../../大客户运费结算日报(一).cll


一开始做的时候很乱,无从下手,从网上找了一个例子,可以用.但是还想应该有更简单的代码.于是根据作者的思路我自己弄出来了,代码少了很多,我感觉比较好理解一些.
就是获得路径后,计算有几个"//",然后根据它,写出几个"../",这样就可以解决了.
获取目录路径的方法是:
public string pathA= System.Windows.Forms.Application.StartupPath.ToString();
然后可以计算了,
下面是我的代码:
public static string paths(string one)
        {
            int p=0;      //p记录你当前项目的几级目录   也就是说有几个"//"          
            one = one.Substring(0, one.Length - 9);     //为什么减9呢,因为  pathA获得的路径包括"/bin/Debug",求的是根目录,所以减9
            string path11 = "dddd";                     //path11  为了显示看得明显

            int i=one.Length;
            for (int j = 0; j < i; j++)
            {
                if (one.Substring(j, 1) == "//")
                {
                    p++;                   
                }
            }
            for (int ss = 1; ss < p; ss++)         
            ///为什么从1开始,因为上面算出的"//"个数要减一个
            /// 相对路径从硬盘根目录上开始,例如:   D://这个   "//"不用计算
            ///
            {
                path11 = "..//" + path11;
            }
            return path11;
        }

我把从网上找的例子也贴出来:
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);
            }

            if (intIndex >= 0)
            {
                strPath2 = strPath2.Substring(intIndex);
                intPos = strPath1.IndexOf("//", intIndex);
                while (intPos >= 0)
                {
                    strPath2 = "..//" + strPath2;
                    intPos = strPath1.IndexOf("//", intPos + 1);
                }
            }
            return strPath2;
        }
希望对大家有用,大家也可以下载源代码,地址是:

http://download.csdn.net/source/573886

请大家多多指教

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值