2

我正在尝试用下划线重命名每个文件的空白区域:

DirectoryInfo dir = new DirectoryInfo(@"Q:\Audio");
var files = (from f in dir.GetFiles() select f.FullName);
files.ToList().ConvertAll( s => s.Replace( " ", "_") );

但它不起作用,我尝试使用 foreach 循环并抱怨“无法分配给'元素',因为它是'foreach 迭代变量'”

我该如何处理?

4

3 回答 3

4

ConvertAll返回一个新的List.

var renamedFiles = files.ToList().ConvertAll(s => s.Replace(" ", "_"));
于 2012-10-12T20:20:00.917 回答
2

您可以使用以下代码块之一:

DirectoryInfo dir = new DirectoryInfo(@"C:\");
var files = (from f in dir.GetFiles() select f.FullName.Replace(" ", "_"));

或者:

DirectoryInfo dir = new DirectoryInfo(@"C:\");
var files = (from f in dir.GetFiles() select f.FullName);
var fileNames = (from fn in files select fn.Replace(" ", "_"));

或者:

DirectoryInfo dir = new DirectoryInfo(@"C:\");
var files = (from f in dir.GetFiles() select f.FullName);
var fileNames = files.Select(s => s.Replace(" ", "_"));

或(坏主意):

DirectoryInfo dir = new DirectoryInfo(@"C:\");
var files = (from f in dir.GetFiles() select f.FullName);
var fileNames = files.ToList().ConvertAll(s => s.Replace(" ", "_"));

编辑 1:但我建议使用 select 函数,最好不要为 IQueryable 等延迟对象调用 .ToList() 方法。

于 2012-10-12T20:26:04.317 回答
0

你实际上需要重置你的变量filesfiles更改最后一行以使用来自的输出重置变量ConvertAll

files = files.ToList().ConvertAll( s => s.Replace( " ", "_") );
于 2012-10-12T20:20:10.057 回答