我创建了一个可以读取 .txt 文件的小程序。
此文件包含指向此格式的另一个文件的链接 new_file.txt
目标是返回新文件的路径,所以基本上我正在这样做:
String newFileName = getFileName();
int index = oldFilePath.lastIndexOf('\\');
String path = oldFilePath.substring(0, index + 1);
String newFilePath = path + newFileName;
return newFilePath;
例如:
我打开的第一个文件是:C:\a\b\c\oldFile.txt
在这个文件中我找到了newFile.txt
因此新路径将是:C:\a\b\c\newFile.txt
很好,但是如果我发现这样的东西怎么办:
..\
或 .\.\
或 ...
有什么方法可以自动化处理这种困惑吗?
谢谢
最佳答案
在 C#/.Net 中,你有相当酷的 Path class .
您可以使用Path.GetFullPath( string pathname )解析路径,例如其中包含 \..\
等。
使用Path.GetDirectory()
、Path.GetFileName()
、Path.GetFileNameWithoutExtension()
& Path.GetExtension( )
将名称分开,Path.Combine()
将它们重新组合在一起。
关于c# - 管理绝对路径和完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7037989/