【问题标题】:Retrieve filename Without extension from file full path从文件完整路径中检索没有扩展名的文件名
【发布时间】:2013-04-07 20:57:41
【问题描述】:

我有一个文件列表,需要从文件完整路径中检索文件名(无扩展名)。

我在命令提示符下生成了一个列表打印(故意在里面包含路径);我需要用其他东西替换路径。

即: [这是带有生成内容示例的 *.txt 文件]

C:\folder\files\img1.png  
C:\folder\files\img2.png  
C:\folder\files\img3.png  
C:\folder\files\img4.png  
...etc...

我想要达到的目标: 图片1.png。或Img1

我正在使用下面的代码,但我还不知道如何正确使用它。

[原码]

File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));

[相同的代码;但修改]

File.WriteAllText(@"C:\Folder\Files\print.txt", Regex.Replace(File.ReadAllText(@"C:\Folder\Files\print.txt"), "[C:\folder\files\]", "Copy "));

【问题讨论】:

  • 尝试 File.WriteAllText(@"C:\Folder\Files\print.txt", Regex.Replace(File.ReadAllText(@"C:\Folder\Files\print.txt"), @"C:\folder\files", "复制"));

标签: c# string replace filenames


【解决方案1】:

这就是你可以使用它的方式。在这种情况下您不需要使用 RegEx,因为您要替换的字符串已经定义好:

File.WriteAllText(@"C:\Folder\Files\print.txt", File.ReadAllText(@"C:\Folder\Files\print.txt").Replace(@"C:\folder\files\", "Copy "));

【讨论】:

  • =D 哇!这么简单!?效果很好。非常感谢“outcoldman”
【解决方案2】:

您不能只使用GetFileName 并提供字符串值吗?您可以将输出附加到字符串生成器,然后重写文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    相关资源
    最近更新 更多