Search code examples
c#stringcollection

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(); 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?


Solution

  • 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>());