[英]How to write contents of System.Collections.Specialized.StringCollection to file?
I have had no luck searching the obvious places for an answer to why using File.WriteAllLines(); 我没有运气搜索显而易见的地方,以回答为什么使用File.WriteAllLines(); doesn't work when outputting a StringCollection: 输出StringCollection时不起作用:
static System.Collections.Specialized.StringCollection infectedLog = new System.Collections.Specialized.StringCollection();
Omitting code here that has populated infectedLog....... 在这里省略已填充的感染日志代码.......
File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog);
Could anyone either tell me what I am doing wrong, or point me in the direction of an explanation that will please? 任何人都可以告诉我我做错了什么,或者指出一个令人满意的解释方向?
The File.WriteAllLines
expects an IEnumerable<string>
(or a string[]
) whereas StringCollection
only implements IEnumerable
(note the lack of generic type). File.WriteAllLines
需要一个IEnumerable<string>
(或一个string[]
),而StringCollection
只实现IEnumerable
(注意缺少泛型类型)。 Try the following: 请尝试以下方法:
using System.Linq;
...
File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());
尝试这个
File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());
The problem is that StringCollection is a really cold collection. 问题是StringCollection是一个非常冷的集合。 It does not implement IEnumerable<T>, and it is not an array, so there is no overload of WriteAllLines for it. 它没有实现IEnumerable <T>,并且它不是一个数组,所以WriteAllLines没有重载。
You can do this: 你可以这样做:
File.WriteAllLines(theFileName, infectedLog.Cast<string>());
Or, you could switch to a more modern collection type, like a List<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.