是否有任何 C# 命令可以删除路径中的“..”?
Is there any C# command to remove the ".." in a path?
我有以下内容:
// 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# 方法可以优雅地做到这一点。如果没有,你推荐什么算法?
谢谢!
您正在寻找 Path.GetFullPath()
。
您可以使用 Path.GetFullPath
方法。此外,您可以删除 Uri
处理:
// 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);
样本测试:
- C:\ConsoleApplication1\ConsoleApplication1\bin\SAMPLE.CMD
@DEBUG\ConsoleApplication1.exe
输出:
C:\ConsoleApplication1\ConsoleApplication1\bin\Xpto\PleaseReadMe.txt
我有以下内容:
// 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# 方法可以优雅地做到这一点。如果没有,你推荐什么算法?
谢谢!
您正在寻找 Path.GetFullPath()
。
您可以使用 Path.GetFullPath
方法。此外,您可以删除 Uri
处理:
// 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);
样本测试:
- C:\ConsoleApplication1\ConsoleApplication1\bin\SAMPLE.CMD
@DEBUG\ConsoleApplication1.exe
输出:
C:\ConsoleApplication1\ConsoleApplication1\bin\Xpto\PleaseReadMe.txt