Подтвердить что ты не робот

Записать список объектов в файл

У меня есть продавец класса в следующем формате:

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

У меня есть еще один класс, в котором пользователь вводит имя, адрес, адрес электронной почты и продажи. Этот ввод затем добавляется в список

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

После того, как пользователь вводит столько продавцов в список, сколько им нравится, у них есть возможность сохранить список в файл по своему выбору (который я могу ограничить .xml или .txt(что когда-либо более подходит)). Как добавить этот список в файл? Также этот файл необходимо перечитать обратно в список, если пользователь хочет позже просмотреть записи.

4b9b3361

Ответ 1

Что-то вроде этого будет работать. это использует двоичный формат (самый быстрый для загрузки), но тот же код применим к 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);
            }
        }
    }

Ответ 2

Я написал сообщение в блоге о сохранении данных объекта в двоичном, 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

Требуется, чтобы сборка 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

Вы должны включить ссылку на сборку Newtonsoft.Json, которую можно получить из Json.NET NuGet Package.

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

Ответ 3

Если вы хотите сериализацию XML, вы можете использовать встроенный сериализатор. Для этого добавьте флаг [Serializable] в класс:

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

Затем вы можете переопределить метод ToString(), который преобразует данные в строку xml:

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() в файл.

UPDATE Вышеупомянутое будет сериализовать одиночную запись как 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;
    }
}

Ответ 4

Если вы хотите использовать JSON, то использовать Json.NET обычно лучше всего.

Если по какой-то причине вы не можете использовать Json.NET, вы можете использовать встроенную поддержку JSON, найденную в .NET.

Вам нужно будет включить следующую инструкцию using и добавить ссылку для System.Web.Extentsions.

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

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