繁体   English   中英

如何将System.Collections.Specialized.StringCollection的内容写入文件?

[英]How to write contents of System.Collections.Specialized.StringCollection to file?

我没有运气搜索显而易见的地方,以回答为什么使用File.WriteAllLines(); 输出StringCollection时不起作用:

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

在这里省略已填充的感染日志代码.......

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

任何人都可以告诉我我做错了什么,或者指出一个令人满意的解释方向?

File.WriteAllLines需要一个IEnumerable<string> (或一个string[] ),而StringCollection只实现IEnumerable (注意缺少泛型类型)。 请尝试以下方法:

using System.Linq;
...
File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());

尝试这个

File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());

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

你可以这样做:

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

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

        using (StreamWriter w = File.AppendText(@"testfile.txt"))
        {
            foreach (var line in sc)
            {
                w.WriteLine(line);
            }
            w.Close();
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM