c# - 管理绝对路径和完整路径

标签 c# java algorithm file automation

我创建了一个可以读取 .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/

相关文章:

c# - VB .Net 等价于 yield break;

java - 提取相对于类路径的资源

algorithm - Scala 中最快的加权随机算法?

c# - 轴在点上绘制并防止在 DataVisualization.Charting 中进行选择

c# - 只修剪空白,不带转义字符

java - Hibernate:使用关联的 findByExample 条件

arrays - 找到其和可被 K 整除的最长子数组

algorithm - 为什么快速排序比归并排序好?

c# - 使用 json.net 检测带有 json 对象的 token

java - 无法使用 ElasticSearch Java API 检索嵌套对象