How to get relative path from absolute path

前端 未结 23 2212
既然无缘
既然无缘 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:46

    Play with something like:

    private String GetRelativePath(Int32 level, String directory, out String errorMessage) {
            if (level < 0 || level > 5) {
                errorMessage = "Find some more smart input data";
                return String.Empty;
            }
            // ==========================
            while (level != 0) {
                directory = Path.GetDirectoryName(directory);
                level -= 1;
            }
            // ==========================
            errorMessage = String.Empty;
            return directory;
        }
    

    And test it

    [Test]
        public void RelativeDirectoryPathTest() {
            var relativePath =
                GetRelativePath(3, AppDomain.CurrentDomain.BaseDirectory, out var errorMessage);
            Console.WriteLine(relativePath);
            if (String.IsNullOrEmpty(errorMessage) == false) {
                Console.WriteLine(errorMessage);
                Assert.Fail("Can not find relative path");
            }
        }
    

提交回复
热议问题