使用子字符串使用c#重命名多个文件名
本文关键字:文件名 字符串 重命名 | 更新日期: 2023-09-27 18:03:23
我需要重命名多个CSV文件名。我想删除"-"之后的所有内容,例如"File-1.csv"将变成"File.csv"。这是我的代码不能工作:
DirectoryInfo d = new DirectoryInfo(@"C:'folder");
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
File.Move(f.FullName, f.FullName.ToString().Substring(0, f.LastIndexOf('-')));
}
我得到这个错误:
错误2 'System.IO。FileInfo'不包含'LastIndexOf'的定义,也没有扩展方法'LastIndexOf'接受类型为'System.IO '的第一个参数。可以找到FileInfo'(您是否缺少using指令或程序集引用?)
我该如何解决这个问题?
你当前的代码没有编译,因为你在FileInfo
对象上调用.LastIndexOf()
时,你应该在FileInfo.FullName
上调用它。您的子字符串还从文件名字符串中删除了扩展名,我认为这不是您想要的。下面是一个保留扩展名的解决方案:
foreach (FileInfo f in infos)
{
// Get the extension string from the existing file
var extension = f.FullName.Substring(f.FullName.LastIndexOf('.'), f.FullName.Length - 1);
// Get the filename, excluding the '-' as well as the extension
var filename = f.FullName.SubString(0, f.FullName.LastIndexOf('-'));
// Concatenate the filename and extension and move the file
File.Move(f.FullName, String.Format("{0}{1}", filename, extension));
}
我得到这个错误:
错误2 'System.IO。FileInfo'不包含一个关于LastIndexOf的定义
f
不是字符串;尝试f.FullName.LastIndexOf…