How to get relative path from absolute path

前端 未结 23 2058
既然无缘
既然无缘 2020-11-22 11:52

There\'s a part in my apps that displays the file path loaded by the user through OpenFileDialog. It\'s taking up too much space to display the whole path, but I don\'t want

23条回答
  •  醉梦人生
    2020-11-22 12:36

    This should work:

    private string rel(string path) {
      string[] cwd  = new Regex(@"[\\]").Split(Directory.GetCurrentDirectory());
      string[] fp   = new Regex(@"[\\]").Split(path);
    
      int common = 0;
    
      for (int n = 0; n < fp.Length; n++) {
        if (n < cwd.Length && n < fp.Length && cwd[n] == fp[n]) {
          common++;
        }
      }
    
      if (common > 0) {
        List rp = new List();
    
        for (int n = 0; n < (cwd.Length - common); n++) {
          rp.Add("..");
        }
    
        for (int n = common; n < fp.Length; n++) {
          rp.Add(fp[n]);
        }
    
        return String.Join("/", rp.ToArray());
      } else {
        return String.Join("/", fp);
      }
    }
    

提交回复
热议问题