C#将文本文件保存到对象中的最佳方法

时间:2014-05-12 18:17:03

标签: c# text-files

我有一组分隔的文本文件,我需要阅读,创建一个类和对象,并在其中存储成员。我是一个初学者,只是想指向正确的方向。任何帮助将非常感激。非常感谢你。

我用以下对象创建了一个类:

public string left;
public string right;

和我的表单代码:

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog of = new OpenFileDialog();
    of.ShowDialog();
    textBox1.Text = of.FileName;
}

private void button2_Click(object sender, EventArgs e)
{
    StreamReader sr = new StreamReader(textBox1.Text);
    textBox2.Text = sr.ReadToEnd();
    // sr.Close();
}

private void button3_Click(object sender, EventArgs e)
{
    string[] split1 = textBox2.Text.Split(';');
    foreach (string segment in split1)
    {
        //split sub-segment
        string[] split2 = segment.Split(':');
        //check if it's valid
        if (split2.Count().Equals(2))
        {
            id textfile = new id();
            textfile.left += // ????
            id textfile1 = new id();
            textfile.right += // ????

3 个答案:

答案 0 :(得分:2)

通常,最好使用JSONXML将数据保存到文本文件而不是分隔文本或自定义格式。这是因为我的语言提供了良好的JSON和XML支持,并且易于使用。

public class MyCustomClass //this class will hold your data
{
    public string Left {get; set;}
    public string Right {get;set;}
}

MyCustomClass mcc=new MyCustomClass(); //create an instance of your class
mcc.Left="yes"; //set some properties
mcc.Right="nope";
string json=JsonConvert.SerializeObject(mcc); //convert to JSON string
File.WriteAllText("mcc.txt",json); //save to file

//later on, when you want to read it back from the file
string json=File.ReadAllText("mcc.text"); //read from file into a string
MyCustomClass mcc=JsonConvert.DeserializeObject<MyCustomClass>(json); //convert the string back to an instance of MyCustomClass

上面,我们使用Json.NET这是一个可用于.NET Framework的库(available on NuGet)。我们使用它将我们的对象转换为字符串(序列化),然后再将其转换回对象(反序列化)。请注意,为了使用JsonConvert类,您需要Json.NET引用并在类using Newtonsoft.Json;的顶部添加using语句。

答案 1 :(得分:2)

您正在寻找的是serialization。如果您具有已知结构(例如具有string leftstring right的类),则需要将该结构写入文本文件。然后,您希望重新读取该信息,并使用每个值自动填充该类。

正如梅森所指出的,JSON相当容易设置。您可以创建所需的类结构,并告诉JSON将其保存到指定的文件中(通过SerializeObject)。

由于.NET允许reflection,因此JSON能够将文本文件转换回class的内容,而无需手动“myClass.left = [some_value_from_json]& #39;

就个人而言,我选择使用JSON或XML,因为命名数据块意味着它更具可读性,并且您的解析器能够处理重新排列数据的人(如果不重要的话)文件在定义left之前定义right。如果重新安排.CSV文件,则会导致数据损坏。

答案 2 :(得分:1)

读取分隔文件很常见,有很多方法可以解决这个问题。我个人使用streamReader读取文件并将其拆分为分隔符:

 Foo foo = new Foo(); // custom class
 string file = "export.CSV";
 if (System.IO.File.Exists(file))
 {             
      // Do work
      using (var reader = new StreamReader(file))
      {
          while (!reader.EndOfStream)
          {
              // split on the delimeter
              var readLine = reader.ReadLine();
              if (readLine == null) continue;
              var lines = readLine.Split(new[] { ',' });

              foreach (string s in lines)
              {
                  // do something with the data from the line

              }  
              // alternatively, you could specify your objects if your files
              // layout never changes. Just be careful to catch the exceptions! 
              foo.bar = lines[0];
              foo.baz = lines[1];

          }
      }
 }
相关问题