5

我没有运气在明显的地方寻找为什么使用 File.WriteAllLines(); 的答案。输出 StringCollection 时不起作用:

static System.Collections.Specialized.StringCollection infectedLog = new System.Collections.Specialized.StringCollection();

在此处省略填充了受感染日志的代码.......

File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog);

谁能告诉我我做错了什么,或者向我指出一个可以取悦的解释的方向?

4

4 回答 4

8

File.WriteAllLines期望 a IEnumerable<string>(或 a string[])而仅StringCollection实现IEnumerable(注意缺少泛型类型)。尝试以下操作:

using System.Linq;
...
File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());
于 2012-02-17T14:03:59.817 回答
1

试试这个

File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());
于 2012-02-17T14:04:08.520 回答
1

问题是 StringCollection 是一个非常冷的集合。它没有实现 IEnumerable<T>,而且它不是一个数组,所以它没有 WriteAllLines 的重载。

你可以这样做:

File.WriteAllLines(theFileName, infectedLog.Cast<string>());

或者,您可以切换到更现代的集合类型,例如 List<string>。

于 2012-02-17T14:08:52.483 回答
0
        using (StreamWriter w = File.AppendText(@"testfile.txt"))
        {
            foreach (var line in sc)
            {
                w.WriteLine(line);
            }
            w.Close();
        }
于 2012-02-17T14:11:58.333 回答