1

I am trying to save the list of data from C# code to a text file. It throws an error at foreach stating that list cannot be converted to string. Any ideas where I am going wrong?

I have to Run Application only on .Net Framework 3.5

IList<FolderDetails> ListToCheck;

 using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
 {
     foreach (string line in ListToCheck)
     {                       
         file.WriteLine(line);                        
     }
}
public class FolderDetails
{
    public string PropertyGroupName { get; set; }
    public string ProjFiles { get; set; }
}
AaronLS
  • 37,329
  • 20
  • 143
  • 202
Kurkula
  • 6,386
  • 27
  • 127
  • 202

3 Answers3

5

Examine this code:

IList<FolderDetails> ListToCheck;

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
{
    foreach (string line in ListToCheck)

You say ListToCheck is a list of objects of type FolderDetail, but in

foreach (string line in ListToCheck)

you try to assert that the type is string instead.

Try something like

foreach (FolderDetail line in ListToCheck)
{
    file.WriteLine(line.SomeAppropriatePropertyOfFolderDetail);
Eric J.
  • 147,927
  • 63
  • 340
  • 553
2

Rework it this way...

Add a ToString() override to your class:

private class FolderDetails
{
    public string PropertyGroupName { get; set; }
    public string ProjFiles { get; set; }
    public override string ToString()
    {
        return string.Format("{0}:{1}", this.PropertyGroupName, this.ProjFiles);
    }
}

Then output like this:

List<FolderDetails> foldersListToCheck = GetFolderDetails();
File.WriteAllLines(@"C:\LogFile.txt", foldersListToCheck.Select(f => f.ToString()));
Shahzad Qureshi
  • 1,776
  • 14
  • 15
  • 1
    That won't compile, will it? The WriteAllLines method requires a collection of strings. Having a ToString method doesn't make an object into a string. – phoog Apr 30 '15 at 18:38
  • AllLines is part of .Net framework 3.5+. My situation is I have to use this code in sharepoint 2010 app which supports 3.5 only. – Kurkula Apr 30 '15 at 18:39
  • 1
    The OP's original StreamWriter.WriteLine has an overload that accepts Object, so that overload will automatically call ToString() to get the appropriate representation. – Eric J. Apr 30 '15 at 18:41
1
IList<FolderDetails> ListToCheck;

 using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
 {
     foreach (string line in ListToCheck)
     {                       
         file.WriteLine(line);                        
     }
}

In the above code ListToCheck is not a list of strings and it is not initialized

Kenner Dev
  • 327
  • 1
  • 4
  • 13