保存/加载类的列表到/从txt

时间:2014-05-21 20:56:25

标签: 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; 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

有没有简单的方法呢?

3 个答案:

答案 0 :(得分:0)

看一下序列化:

http://tech.pro/tutorial/618/csharp-tutorial-serialize-objects-to-a-file

在页面的最后,您还可以找到一个示例!

答案 1 :(得分:0)

要将列表保存到文件,可能是这样的:

  // 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();

那说......的确,如果你想从文件中加载列表,使用序列化将是最好的方法。

答案 2 :(得分:0)

我有一个类似的问题。 NewtonSoft是我的最佳选择。试试看。 创建一个Album对象的实例,例如albumObj,然后将该类序列化为一个文件

Album albumObj = new Album();

File.WriteAllText(@"C:\yourDirectory\example.json", JsonConvert.SerializeObject(albumObj));

Album中具有“获取”访问器的所有公共属性都将被序列化。 您可以使用Formatting.Indented来提高数据的可读性,也可以使用JsonIgnore来忽略某些属性。 看起来像这样

File.WriteAllText(@"C:\yourDirectory\example.json", JsonConvert.SerializeObject(albumObj, Formatting.Indented));
  

不要忘记为NewtonSoft.Json安装软件包。   为此,请转到“工具”->“ NuGet程序包管理器”->“程序包管理器控制台”,然后粘贴Install-Package Newtonsoft.Json,然后按Enter。

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