Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.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#_.net_File_Text - Fatal编程技术网

C# 读取和写入名称值文本文件的简单方法

C# 读取和写入名称值文本文件的简单方法,c#,.net,file,text,C#,.net,File,Text,我有很多领域的课程 public class CrowdedHouse { public int value1; public float value2; public Guid value3; public string Value4; // some more fields below } 我的类必须按以下格式(反)序列化为简单的Windows文本文件 NAME1=VALUE1 NAME2=VALUE2 在.NET中最方便的方法是什么?这是一个文

我有很多领域的课程

public class CrowdedHouse
{
  public int     value1;
  public float   value2;
  public Guid    value3;
  public string  Value4;

  // some more fields below
}
我的类必须按以下格式(反)序列化为简单的Windows文本文件

NAME1=VALUE1
NAME2=VALUE2
在.NET中最方便的方法是什么?这是一个文本文件,所有值必须首先转换为字符串。假设我已经将所有数据转换为字符串

更新一个选项是pinvoke WritePrivateProfileString/WritePrivateProfileString 但它们使用的是我不需要使用的必需“[Section]”字段。

编写起来很简单:

// untested
using (var file = System.IO.File.CreateText("data.txt"))
{
   foreach(var item in data)
      file.WriteLine("{0}={1}", item.Key, item.Value);
}
为了回过头来阅读:

// untested
using (var file = System.IO.File.OpenText("data.txt"))
{
   string line;
   while ((file.ReadLine()) != null)
   {
       string[] parts = line.Split('=');
       string key = parts[0];
       string value = parts[1];
       // use it
   }
}

但最好的答案可能是:使用XML。

编辑:如果您已经将每个数据值转换为字符串,只需在创建这些值的
字典后使用以下方法将其序列化:

var dict = new Dictionary<string, string>
{
    { "value1", "value1value" },
    { "value2", "value2value" },
    // etc
}
要将字典转换为文件,请使用:

string[] lines = dict.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray();
File.WriteAllLines(lines);

请注意,您的
名称
s和
s不能包含
=

答案的微小改进:

要启用=在值中:(将仅拆分一次)


如果值部分中有一个“=”,这将导致问题。不,值和名称部分都不包含“=”字符。也许您应该指定“数据”是什么。我假设有一个字典。这对我来说很有效,但我必须修改编写代码,我必须向
writeAllines
方法添加第二个参数<代码>文件.writeAllines(@“C:\myFolder\myFile.txt”,行)谢谢。
string[] lines = dict.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray();
File.WriteAllLines(lines);
var dict = lines.Select(l => l.Split(new[]{'='},2)).ToDictionary(a => a[0], a => a[1]);