Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在txt中保存/加载类列表_C# - Fatal编程技术网

C# 在txt中保存/加载类列表

C# 在txt中保存/加载类列表,c#,C#,我有这样一个简单的类列表 public class Album { public int IDNumber { get; set; } public string AlbumName { get; set; } public string Artist { get; set; } public int ReleaseDate { get; set; } public int TrackAmount { get; se

我有这样一个简单的类列表

  public class Album
   {
       public int IDNumber { get; set; }
       public string AlbumName { get; set; }
       public string Artist { get; set; }
       public int ReleaseDate { get; set; }
       public int TrackAmount { get; set; }
       public string Location { get; set; }
       public int Rating { get; set; }

       public Album(int _id, string _name, string _artist, int _releasedate, int _trackamount, string _location, int _rating)
       {
           IDNumber = _id;
           AlbumName = _name;
           Artist = _artist;
           ReleaseDate = _releasedate;
           TrackAmount = _trackamount;
           Location = _location;
           Rating = _rating;
       }
   }
我需要将它保存到文件中,并从一个文件读取到另一个列表。我对C语言相当陌生,我的C++方法根本不管用。有什么简单的方法可以做到这一点吗?我希望它在文件中看起来像这样:

id albumname artist releasedate trackamout location rating
有什么简单的方法吗?

看看


在页面的最后,你会发现一个例子,以及

要将列表保存到文件中,可以如下所示:

  // create a writer and open the file
  StreamWriter stream = new StreamWriter("myfile.txt");

  foreach(Album album in myListOfAlbum)
  {
    // write a line of text to the file
    stream.WriteLine(
      album.IDNumber.ToString() + " " + 
      album.AlbumName.ToString() + " " + 
      ...
      ...
    );
  }

  // close the stream
  stream.Close();
也就是说。。。事实上,如果您也想从文件中加载列表,那么使用序列化将是最好的方法。

我有一个类似的问题。是我被建议使用的,非常好。试试看。 创建
Album
对象的实例,例如
albumObj
,然后将该类序列化为文件,如下所示:

Album albumObj = new Album();

File.WriteAllText(@"C:\yourDirectory\example.json", JsonConvert.SerializeObject(albumObj));
Album
中具有“get”访问器的所有公共属性都将被序列化。 您可以使用
Formatting.Indented
使数据更具可读性,或者使用
JsonIgnore
忽略某些属性。 看起来是这样的

File.WriteAllText(@"C:\yourDirectory\example.json", JsonConvert.SerializeObject(albumObj, Formatting.Indented));
不要忘记为安装软件包。 您可以通过进入工具->NuGet Package Manager->软件包管理器控制台,然后粘贴
安装软件包Newtonsoft.Json
并按enter键来完成此操作


之后,您现在可以使用Newtonsoft.Json导入

,您需要的是术语“序列化”。我相信你会在网上找到很多关于如何“序列化类/结构”的例子。