C# 将对象列表写入文件
我有一个班级销售员,格式如下:C# 将对象列表写入文件,c#,list,serialization,C#,List,Serialization,我有一个班级销售员,格式如下: class salesman { public string name, address, email; public int sales; } 我还有一个类,用户在其中输入姓名、地址、电子邮件和销售额。 然后将该输入添加到列表中 List<salesman> salesmanList = new List<salesman>(); List salesmanList=new List(); 在用户向列表中输入任意数量
class salesman
{
public string name, address, email;
public int sales;
}
我还有一个类,用户在其中输入姓名、地址、电子邮件和销售额。
然后将该输入添加到列表中
List<salesman> salesmanList = new List<salesman>();
List salesmanList=new List();
在用户向列表中输入任意数量的销售人员后,他们可以选择将列表保存到自己选择的文件中(我可以将其限制为.xml或.txt(更合适))。
如何将此列表添加到文件中?
此外,如果用户希望以后查看记录,则需要将此文件重新读回列表。如果需要xml序列化,可以使用内置序列化程序。要实现这一点,请向类添加[Serializable]标志:
[Serializable()]
class salesman
{
public string name, address, email;
public int sales;
}
然后,可以重写将数据转换为xml字符串的“ToString()”方法:
public override string ToString()
{
string sData = "";
using (MemoryStream oStream = new MemoryStream())
{
XmlSerializer oSerializer = new XmlSerializer(this.GetType());
oSerializer.Serialize(oStream, this);
oStream.Position = 0;
sData = Encoding.UTF8.GetString(oStream.ToArray());
}
return sData;
}
然后创建一个方法,将this.ToString()
写入文件
更新
上面提到的将单个条目序列化为xml。如果需要对整个列表进行序列化,则想法会有所不同。在这种情况下,如果列表的内容是可序列化的,那么列表是可序列化的,并且在某些外部类中使用序列化
示例代码:
[Serializable()]
class salesman
{
public string name, address, email;
public int sales;
}
class salesmenCollection
{
List<salesman> salesmanList;
public void SaveTo(string path){
System.IO.File.WriteAllText (path, this.ToString());
}
public override string ToString()
{
string sData = "";
using (MemoryStream oStream = new MemoryStream())
{
XmlSerializer oSerializer = new XmlSerializer(this.GetType());
oSerializer.Serialize(oStream, this);
oStream.Position = 0;
sData = Encoding.UTF8.GetString(oStream.ToArray());
}
return sData;
}
}
[Serializable()]
班级推销员
{
公共字符串名称、地址、电子邮件;
公开销售;
}
类销售集合
{
销售员名单;
公共void保存到(字符串路径){
System.IO.File.WriteAllText(路径,this.ToString());
}
公共重写字符串ToString()
{
字符串sData=“”;
使用(MemoryStream oStream=new MemoryStream())
{
XmlSerializer oSerializer=新的XmlSerializer(this.GetType());
序列化(oStream,this);
oStream.Position=0;
sData=Encoding.UTF8.GetString(oStream.ToArray());
}
返回sData;
}
}
像这样的东西会有用的。这使用二进制格式(加载速度最快),但相同的代码将应用于具有不同序列化程序的xml
using System.IO;
[Serializable]
class salesman
{
public string name, address, email;
public int sales;
}
class Program
{
static void Main(string[] args)
{
List<salesman> salesmanList = new List<salesman>();
string dir = @"c:\temp";
string serializationFile = Path.Combine(dir, "salesmen.bin");
//serialize
using (Stream stream = File.Open(serializationFile, FileMode.Create))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bformatter.Serialize(stream, salesmanList);
}
//deserialize
using (Stream stream = File.Open(serializationFile, FileMode.Open))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
List<salesman> salesman = (List<salesman>)bformatter.Deserialize(stream);
}
}
}
使用System.IO;
[可序列化]
班级推销员
{
公共字符串名称、地址、电子邮件;
公开销售;
}
班级计划
{
静态void Main(字符串[]参数)
{
List salesmanList=新列表();
字符串dir=@“c:\temp”;
string serializationFile=Path.Combine(dir,“salesmen.bin”);
//连载
使用(Stream=File.Open(serializationFile,FileMode.Create))
{
var bformatter=new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
序列化(流,salesmanList);
}
//反序列化
使用(Stream=File.Open(serializationFile,FileMode.Open))
{
var bformatter=new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
列表销售员=(列表)bformatter.Deserialize(流);
}
}
}
我刚刚写过;很好地将一个对象或对象列表写入一个文件。以下是各种格式的函数。有关更多详细信息,请参阅我的博客文章
二元的
//
///将给定对象实例写入二进制文件。
///对象类型(以及所有子类型)必须用[Serializable]属性修饰。
///要防止变量被序列化,请使用[NonSerialized]属性对其进行修饰;无法应用于属性。
///
///正在写入XML文件的对象的类型。
///要将对象实例写入的文件路径。
///要写入XML文件的对象实例。
///如果为false,则文件将被覆盖(如果它已存在)。如果为true,则内容将附加到文件中。
公共静态void WriteToBinaryFile(字符串文件路径,T objectToWrite,bool append=false)
{
使用(Stream-Stream=File.Open(filePath,append?FileMode.append:FileMode.Create))
{
var binaryFormatter=new System.Runtime.Serialization.Formatters.Binary.binaryFormatter();
序列化(流,objectToWrite);
}
}
///
///从二进制文件读取对象实例。
///
///要从XML中读取的对象的类型。
///从中读取对象实例的文件路径。
///返回从二进制文件读取的对象的新实例。
公共静态T ReadFromBinaryFile(字符串文件路径)
{
使用(Stream=File.Open(filePath,FileMode.Open))
{
var binaryFormatter=new System.Runtime.Serialization.Formatters.Binary.binaryFormatter();
返回(T)二进制格式化程序。反序列化(流);
}
}
XML
需要在项目中包含System.Xml程序集
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
//
///将给定对象实例写入XML文件。
///只有公共属性和变量才会写入文件。但是,它们可以是任何类型,甚至是其他类。
///如果存在不希望写入文件的公共属性/变量,请使用[XmlIgnore]属性对其进行修饰。
///对象类型必须具有无参数构造函数。
///
///正在写入文件的对象的类型。
///要将对象实例写入的文件路径。
///要写入文件的对象实例。
///如果为false,则文件将被覆盖(如果它已存在)。如果为true,则内容将附加到文件中。
公共静态void WriteToXmlFile(字符串文件路径,T objectToWrite,bool append=false),其中T:new()
{
TextWriter=null;
尝试
{
var serializer=newxmlserializer(typeof(T));
writer=newstreamwriter(文件路径,追加);
serializer.Serialize(writer,objectToWrite);
}
最后
{
if(writer!=null)
writer.Close();
}
}
///
///从XML文件读取对象实例。
///对象类型必须具有无参数构造函数。
///
///要从文件中读取的对象的类型。
///从中读取对象实例的文件路径。
///返回t的新实例
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
// Write the list of salesman objects to file.
WriteToXmlFile<List<salesman>>("C:\salesmen.txt", salesmanList);
// Read the list of salesman objects from the file back into a variable.
List<salesman> salesmanList = ReadFromXmlFile<List<salesman>>("C:\salesmen.txt");
using System.Web.Script.Serialization;
//Deserialize JSON to your Object
YourObject obj = new JavaScriptSerializer().Deserialize<YourObject>("File Contents");
//Serialize your object to JSON
string sJSON = new JavaScriptSerializer().Serialize(YourObject);