是否有任何C#命令删除路径中的“..”?

时间:2015-06-01 21:31:59

标签: c# file-io

我有以下内容:

// Get my executable's path
string exeFile = ( new System.Uri( Assembly.GetEntryAssembly().CodeBase ) ).AbsolutePath;

// Get its directory
string exeFolder = Path.GetDirectoryName( exeFile );

// Get rid of those %20 and stuff
exeFolder = Uri.UnescapeDataString( exeFolder );

// Get some relative path from my .config file
string relativePath = ConfigurationManager.AppSettings["MyRelativePath"] );

// Woa. The final result, uff.
string myFinalPath = Path.Combine( exeFolder, relativePath );

现在,如果MyRelativePath类似..\Xpto\PleaseReadMe.txt且我的可执行文件位于C:\Ypto\RunMe.exe,我将以:

结束

C:\Ypto\..\Xpto\PleaseReadMe.txt

而不是

C:\Xpto\PleaseReadeMe.txt

考虑到我必须在文本框中显示此路径,当然我不希望用户看到丑陋的“\ Ypto ..”部分。我可以轻松地创建一个包含几行的函数来解析这个字符串并删除这些结构,但我想知道是否有一个优雅地执行此操作的C#方法。如果没有,你推荐什么算法?

谢谢!

2 个答案:

答案 0 :(得分:2)

您正在寻找Path.GetFullPath()

答案 1 :(得分:1)

您可以使用Path.GetFullPath方法。此外,您可以删除CMakeLists.txt处理:

Uri

样品测试:

  • C:\ ConsoleApplication1 \ ConsoleApplication1 \ BIN \ SAMPLE.CMD // Get my executable's path string exeFile = Assembly.GetEntryAssembly().Location; // Get its directory string exeFolder = Path.GetDirectoryName( exeFile ); // Get some relative path from my .config file string relativePath = @"..\Xpto\PleaseReadMe.txt"; // Woa. The final result, uff. string myFinalPath = Path.GetFullPath(Path.Combine(exeFolder, relativePath)); Console.WriteLine(myFinalPath);

输出:

@DEBUG\ConsoleApplication1.exe