将列表数据添加到文本文件
Adding List Data to a Text File
我正在尝试将数据列表从 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; }
}
检查这段代码:
IList<FolderDetails> ListToCheck;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
{
foreach (string line in ListToCheck)
你说ListToCheck是一个FolderDetail类型的对象列表,但是在
foreach (string line in ListToCheck)
您尝试断言类型为字符串。
试试
foreach (FolderDetail line in ListToCheck)
{
file.WriteLine(line.SomeAppropriatePropertyOfFolderDetail);
这样修改...
将 ToString() 覆盖添加到您的 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);
}
}
然后输出如下:
List<FolderDetails> foldersListToCheck = GetFolderDetails();
File.WriteAllLines(@"C:\LogFile.txt", foldersListToCheck.Select(f => f.ToString()));
IList<FolderDetails> ListToCheck;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
{
foreach (string line in ListToCheck)
{
file.WriteLine(line);
}
}
上面代码中的ListToCheck不是字符串列表,也没有初始化
我正在尝试将数据列表从 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; }
}
检查这段代码:
IList<FolderDetails> ListToCheck;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
{
foreach (string line in ListToCheck)
你说ListToCheck是一个FolderDetail类型的对象列表,但是在
foreach (string line in ListToCheck)
您尝试断言类型为字符串。
试试
foreach (FolderDetail line in ListToCheck)
{
file.WriteLine(line.SomeAppropriatePropertyOfFolderDetail);
这样修改...
将 ToString() 覆盖添加到您的 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);
}
}
然后输出如下:
List<FolderDetails> foldersListToCheck = GetFolderDetails();
File.WriteAllLines(@"C:\LogFile.txt", foldersListToCheck.Select(f => f.ToString()));
IList<FolderDetails> ListToCheck;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
{
foreach (string line in ListToCheck)
{
file.WriteLine(line);
}
}
上面代码中的ListToCheck不是字符串列表,也没有初始化