C# 将对象列表写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16352879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:49:18  来源:igfitidea点击:

write list of objects to a file

c#listserialization

提问by Pindo

I've got a class salesman in the following format:

我有以下格式的班级推销员:

class salesman
{
    public string name, address, email;
    public int sales;
}

I've got another class where the user inputs name, address, email and sales. This input is then added to a list

我有另一个类,用户可以在其中输入姓名、地址、电子邮件和销售额。然后将此输入添加到列表中

List<salesman> salesmanList = new List<salesman>();

After the user has input as many salesman to the list as they like, they have the option to save the list to a file of their choice (which I can limit to .xml or .txt(which ever is more appropriate)). How would I add this list to the file? Also this file needs to be re-read back into a list if the user wishes to later view the records.

在用户将尽可能多的销售员输入到列表中后,他们可以选择将列表保存到他们选择的文件中(我可以将其限制为 .xml 或 .txt(哪个更合适))。我如何将此列表添加到文件中?此外,如果用户希望稍后查看记录,则需要将该文件重新读回到列表中。

采纳答案by Matt Johnson

Something like this would work. this uses a binary format (the fastest for loading) but the same code would apply to xml with a different serializer.

像这样的事情会起作用。这使用二进制格式(加载速度最快),但相同的代码适用于具有不同序列化程序的 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);
            }
        }
    }

回答by naivists

If you want xml serialization, you can use the built-in serializer. To achieve this, add [Serializable] flag to the class:

如果你想要 xml 序列化,你可以使用内置的序列化器。为此,请向类添加 [Serializable] 标志:

[Serializable()]
class salesman
{
    public string name, address, email;
    public int sales;
}

Then, you could override the "ToString()" method which converts the data into xml string:

然后,您可以覆盖将数据转换为 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;
    }

Then just create a method that writes this.ToString()into a file.

然后只需创建一个写入this.ToString()文件的方法。

UPDATE The mentioned above will serialize single entry as xml. If you need the whole list to be serialized, the idea would be a bit different. In this case you'd employ the fact that lists are serializable if their contents are serializable and use the serialization in some outer class.

更新 上面提到的将单个条目序列化为 xml。如果您需要序列化整个列表,则想法会有所不同。在这种情况下,如果列表的内容是可序列化的,并且在某个外部类中使用序列化,那么您将使用列表是可序列化的事实。

Example code:

示例代码:

[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;
    }
}

回答by deadlydog

I just wrote a blog post on saving an object's data to Binary, XML, or Json; well writing an object or list of objects to a file that is. Here are the functions to do it in the various formats. See my blog post for more details.

我刚刚写了一篇关于将对象数据保存为 Binary、XML 或 Json 的博客文章;很好地将一个对象或对象列表写入文件。以下是以各种格式执行此操作的函数。有关更多详细信息,请参阅我的博客文章。

Binary

二进制

/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the XML 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 XML 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 WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(stream, objectToWrite);
    }
}

/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the XML.</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 binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
    using (Stream stream = File.Open(filePath, FileMode.Open))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        return (T)binaryFormatter.Deserialize(stream);
    }
}

XML

XML

Requires the System.Xml assembly to be included in your project.

需要将 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();
    }
}

Json

杰森

You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.

您必须包含对 Newtonsoft.Json 程序集的引用,该程序集可以从Json.NET NuGet 包中获得

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

Example

例子

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

回答by TRock

If you want to use JSON then using Json.NET is usually the best way to go.

如果你想使用 JSON,那么使用 Json.NET 通常是最好的方法。

If for some reason you are unable to use Json.NET you can use the built in JSON support found in .NET.

如果由于某种原因您无法使用 Json.NET,您可以使用 .NET 中的内置 JSON 支持。

You will need to include the following using statement and add a reference for System.Web.Extentsions.

您需要包含以下 using 语句并添加对System.Web.Extentsions的引用

using System.Web.Script.Serialization;

Then you would use these to Serialize and Deserialize your object.

然后您将使用这些来序列化和反序列化您的对象。

//Deserialize JSON to your Object
YourObject obj = new JavaScriptSerializer().Deserialize<YourObject>("File Contents");

//Serialize your object to JSON
string sJSON = new JavaScriptSerializer().Serialize(YourObject);

https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer_methods(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer_methods(v=vs.110).aspx