How to get relative path from absolute path

前端 未结 23 2056
既然无缘
既然无缘 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条回答
  •  -上瘾入骨i
    2020-11-22 12:44

    If you are using .NET Core 2.0, Path.GetRelativePath() is available providing this specific functionality:

            var relativeTo = @"C:\Program Files\Dummy Folder\MyProgram";
            var path = @"C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat";
    
            string relativePath = System.IO.Path.GetRelativePath(relativeTo, path);
    
            System.Console.WriteLine(relativePath);
            // output --> Data\datafile1.dat 
    

    Otherwise, for .NET full framework (as of v4.7) recommend using one of the other suggested answers.

提交回复
热议问题