How to write the contents of a System.Collections.Specialized.StringCollection file to a file?

I was not lucky to find obvious places to answer the question why using File.WriteAllLines (); does not work on StringCollection output:

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

Omitting here the code that is populated by the infected log .......

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

Can someone tell me what I'm doing wrong, or point me in the direction of an explanation that I like?

+4
source share
4 answers

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

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

try it

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

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

You can do it:

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

Or you can switch to a more modern type of collection, such as List <string>.

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

Source: https://habr.com/ru/post/1397035/


All Articles