我正在尝试将C#代码中的数据列表保存到文本文件中。它在foreach
处抛出一个错误,指出该列表无法转换为字符串。我出错的任何想法?
我必须仅在.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; }
}
答案 0 :(得分:2)
以这种方式重做......
向您的班级添加ToString()覆盖:
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);
}
}
然后像这样输出:
List<FolderDetails> foldersListToCheck = GetFolderDetails();
File.WriteAllLines(@"C:\LogFile.txt", foldersListToCheck.Select(f => f.ToString()));
答案 1 :(得分:1)
IList<FolderDetails> ListToCheck;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
{
foreach (string line in ListToCheck)
{
file.WriteLine(line);
}
}
在上面的代码中,ListToCheck不是字符串列表,也没有初始化