首页 > 解决方案 > 如何将包含另一个列表的列表保存到文件中

问题描述

所以我有我的用户对象:

public class UserModel
{
    public int Id { get; set; }
    public string Username { get; set; }
    public List<ProjectModel> Projects { get; set; }
}

如您所见,我有一个属于用户的项目列表。为了拯救我的用户,我做了这个功能:

    public void AddNewUser(UserModel user)
    {
        try
        {
            string folder = @"c:\temp\";
            StreamWriter sw = new StreamWriter($"{folder}input.txt", append: true);

            sw.WriteLine($"{user.Id}," +
                $"{user.Username}");

            sw.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine($"The file could not be read: {e.Message}");
        }
    }

但是现在我有这个问题,如何保存项目列表并关联到用户。我知道我可以将每个项目保存到另一个文件或保存到同一个文件,但我怎样才能将它们关联起来?

标签: c#listfilesavestreamwriter

解决方案


推荐阅读