Clark Chan

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  105 随笔 :: 0 文章 :: 181 评论 :: 4 引用
C#-计算相对路径


   /// <summary>
        
/// 计算相对路径
        
/// 后者相对前者的路径。
        
/// </summary>
        
/// <param name="mainDir">主目录</param>
        
/// <param name="fullFilePath">文件的绝对路径</param>
        
/// <returns>fullFilePath相对于mainDir的路径</returns>
        
/// <example>
        
/// @"..\..\regedit.exe" = GetRelativePath(@"D:\Windows\Web\Wallpaper\", @"D:\Windows\regedit.exe" );
        
/// </example>

        public static string GetRelativePath(string mainDir, string fullFilePath)
        
{
            
if (!mainDir.EndsWith("\\"))
            
{
                mainDir 
+= "\\"
            }


            
int intIndex = -1, intPos = mainDir.IndexOf('\\');
          
            
while (intPos >= 0)
            
{
                intPos
++;
                
if (string.Compare(mainDir, 0, fullFilePath, 0, intPos, true!= 0break;
                intIndex 
= intPos;
                intPos 
= mainDir.IndexOf('\\', intPos);
            }


              
if (intIndex >= 0)
            
{
                fullFilePath 
= fullFilePath.Substring(intIndex);
                intPos 
= mainDir.IndexOf("\\", intIndex);
                
while (intPos >= 0)
                
{
                    fullFilePath 
= "..\\" + fullFilePath;
                    intPos 
= mainDir.IndexOf("\\", intPos + 1);
                }

            }

           
            
return fullFilePath;
        }


posted on 2008-07-20 17:54 Clark Chan 阅读(250) 评论(0)  编辑 收藏 所属分类: C#技术总结

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-07-20 18:09 编辑过
"五向定位"职业成长路线公开课(上海、南京、大连)
Google站内搜索


相关链接: