我有像这样的类的简单列表。
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有什么简单的方法吗?
发布于 2014-05-22 04:59:14
看看serialization吧。
在页面的末尾,你也会找到一个例子!
发布于 2014-05-22 05:03:50
要将列表保存到文件中,可能如下所示:
// 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();也就是说..。实际上,如果您也想从文件中加载列表,那么使用序列化将是最好的方法。
发布于 2019-08-15 21:34:29
我也有类似的问题。我被推荐使用NewtonSoft,这是非常好的。试一试。创建一个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));不要忘记为NewtonSoft.Json安装软件包。您可以通过转到Tools->NuGet Package Manager-> Package Manager Console,然后粘贴
Install-Package Newtonsoft.Json并按enter键来完成此操作。
之后,您现在可以导入using Newtonsoft.Json
https://stackoverflow.com/questions/23793636
复制相似问题