如何在c#中的文本文件中写入或读取对象数组?

时间:2015-10-07 13:34:55

标签: c#

我有数据存储类的对象数组,我试图在文本文件中写...(这不是完整的代码)

class Program
{
    public int i;

    static void Main(string[] args)
    {
        Program p = new Program();

        user[] obj = new user[10];
        for ( p.i = 0; p.i < 10; p.i++)
        obj[p.i] = new user();
        int index = 0;

2 个答案:

答案 0 :(得分:2)

让你的班级看起来像这样:

[Serializable()]    //Set this attribute to all the classes that want to serialize
public class User : ISerializable //derive your class from ISerializable
{
    public int userInt;
    public string userName;

    //Default constructor
    public User()
    {
        userInt = 0;
        userName = "";
    }

   //Deserialization constructor.
   public User(SerializationInfo info, StreamingContext ctxt)
   {
      //Get the values from info and assign them to the appropriate properties
      userInt = (int)info.GetValue("UserInt", typeof(int));
      userName = (String)info.GetValue("UserName", typeof(string));
   }

   //Serialization function.
   public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
   {
      //You can use any custom name for your name-value pair. But make sure you
      // read the values with the same name. For ex:- If you write userInt as "UserInt"
      // then you should read the same with "UserInt"
      info.AddValue("UserInt", userInt);
      info.AddValue("UserName", userName);
  }
}

现在读取和写入你可以做到这些:

User user=new User();

using(StreamWriter sw=new StreamWriter(/*Filename goes here*/))
{
  using(BinaryFormatter bformatter=new BinaryFormatter())
  {
    bformatter.Serialize(sw, user);
  }
}

using(StreamReader sr=new StreamReader(/*Filename goes here*/))
{
  using(BinaryFormatter bformatter=new BinaryFormatter())
  {
    user=(User)bformatter.Deserialize(sr);
  }
}

我从http://www.codeproject.com/Articles/1789/Object-Serialization-using-C

获得了很多代码

答案 1 :(得分:0)

如果您想读取或写入文本文件,我建议您查看 System.IO Streamreader / Streamwriter Class

看看: https://msdn.microsoft.com/en-us/library/system.io.streamreader%28v=vs.110%29.aspx