绝对路径:
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.youkuaiyun.com/source/573886
请大家多多指教