Search code examples
c#listforeachnotepad

Adding List Data to a Text File


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; }
}

Solution

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