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

发布于 2025-01-06 23:23:03 字数 407 浏览 2 评论 0原文

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

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

在这里省略已填充 InfectedLog 的代码......

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

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

I have had no luck searching the obvious places for an answer to why using File.WriteAllLines(); doesn't work when outputting a 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

无可置疑 2025-01-13 23:23:03

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

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

The File.WriteAllLines expects an IEnumerable<string> (or a string[]) whereas StringCollection only implements IEnumerable (note the lack of generic type). Try the following:

using System.Linq;
...
File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());
人间不值得 2025-01-13 23:23:03

试试这个

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

try this

File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());
恏ㄋ傷疤忘ㄋ疼 2025-01-13 23:23:03

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

您可以这样做:

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

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

The problem is that StringCollection is a really cold collection. It does not implement IEnumerable<T>, and it is not an array, so there is no overload of WriteAllLines for it.

You can do this:

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

Or, you could switch to a more modern collection type, like a List<string>.

德意的啸 2025-01-13 23:23:03
        using (StreamWriter w = File.AppendText(@"testfile.txt"))
        {
            foreach (var line in sc)
            {
                w.WriteLine(line);
            }
            w.Close();
        }
        using (StreamWriter w = File.AppendText(@"testfile.txt"))
        {
            foreach (var line in sc)
            {
                w.WriteLine(line);
            }
            w.Close();
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文