5

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?

M.Babcock
  • 18,753
  • 6
  • 54
  • 84

4 Answers4

8

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>());
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
1

try this

File.WriteAllLines(@"C:\CustomSearchInfectedFiles.txt", infectedLog.Cast<string>());
L.B
  • 114,136
  • 19
  • 178
  • 224
1

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>.

JMarsch
  • 21,484
  • 15
  • 77
  • 125
0
        using (StreamWriter w = File.AppendText(@"testfile.txt"))
        {
            foreach (var line in sc)
            {
                w.WriteLine(line);
            }
            w.Close();
        }
paramosh
  • 2,258
  • 1
  • 15
  • 23