Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#将文本文件保存到对象中的最佳方式_C#_Text Files - Fatal编程技术网

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

C#将文本文件保存到对象中的最佳方式,c#,text-files,C#,Text Files,我有一组需要读取、创建类和对象以及在其中存储成员的分隔文本文件。我是一个初学者,只是希望被指向正确的方向。任何帮助都将不胜感激。多谢各位 我创建了一个包含以下对象的类: public string left; public string right; 及我的表格编号: private void button1_Click(object sender, EventArgs e) { OpenFileDialog of = new OpenFileDialog(); of.Show

我有一组需要读取、创建类和对象以及在其中存储成员的分隔文本文件。我是一个初学者,只是希望被指向正确的方向。任何帮助都将不胜感激。多谢各位

我创建了一个包含以下对象的类:

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 += // ????

通常,最好使用或将数据保存到文本文件,而不是分隔文本或自定义格式。这是因为在我的语言中有很好的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
public class MyCustomClass//此类将保存您的数据
{
左公共字符串{get;set;}
公共字符串权限{get;set;}
}
MyCustomClass mcc=新的MyCustomClass()//创建类的实例
mcc.Left=“是”//设置一些属性
mcc.Right=“不”;
字符串json=JsonConvert.SerializeObject(mcc)//转换为JSON字符串
writealText(“mcc.txt”,json)//保存到文件
//稍后,当您想从文件中读回它时
字符串json=File.ReadAllText(“mcc.text”)//从文件读入字符串
MyCustomClass mcc=JsonConvert.DeserializeObject(json)//将字符串转换回MyCustomClass的实例

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

读取带分隔符的文件是很常见的,有很多方法可以解决这个问题。就我个人而言,我使用a读入文件并在分隔符上拆分它:

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

          }
      }
 }

你要找的是。当你有一个已知的结构时(比如你的类有
string left
string right
),你想把这个结构写到一个文本文件中。然后,您希望读回该信息,并用每个值自动填充该类

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

由于.NET允许,JSON能够将文本文件转换回
类的内容
,而无需手动“myClass.left=[some_value_from_JSON]”


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

我不清楚您到底在问什么。对不起,c#。忘了添加了,你确定要使用分隔文本,而不是JSON或XML等更强大的解决方案吗?我只需要读入文本文件,而不是显示它,我需要将其存储到字符串列表中,我愿意接受建议,我对这个还是很陌生,这就是我学习的方法。如果有一个内部逗号会发生什么?我唯一错过的是存储每个分割的值,这就是我挂断的。我不想显示它,只是将对象存储为list@masoncsv文件有许多方法和缺陷(嵌入的逗号就是其中之一),并且有许多比我的快速代码更好的库。就我个人而言,对于分隔文件,我喜欢制表符,很少能找到嵌入的
\t
:-)我的观点是,分隔文件有很多陷阱,实现将数据保存为JSON、XML、,或者其他一些受良好支持的格式。@mason-I支持不能使用JSON的遗留系统,并且部分支持XML。到处都没有JSON/XML的商业案例,分隔文件可能会存在很长一段时间。我理解你的观点,但OP询问了分隔文件。