从文本文件

时间:2015-11-26 11:55:53

标签: c#

我想将变量存储在.txt文件中 - 就像我总是在人config.txt文件中看到的那样:

var_name = ['"test url"']

我已经得到下面的代码打开文件并读取它(此时只是调试并显示文件中的内容,目前只有1个变量)

System.IO.StreamReader myFile = new System.IO.StreamReader("C:\\conf\\config.txt");
string myString = myFile.ReadToEnd();

myFile.Close();

MessageBox.Show(myString);

文件中的内容是

file_name="C:\\test.txt"

现在我希望能够在VB形式的函数中使用该变量。我该怎么做呢?而且,我怎么能做多个;所以我基本上可以获得表单在启动时加载的大型变量列表?

例如:

// Opens file and reads all variables
// Saves all variables to form
// Can now use varaible in form, e.g. messageBox.Show(file_name);

我是C#的新手,我想它与包含类似但是包含是本地而不是项目的一部分。

2 个答案:

答案 0 :(得分:0)

Disclamer:标准练习(即Settings)通常是最佳政策,但问题已被提出并可以回答:

我建议使用词典,例如

  Dictionary<String, String> MySettings = File
    .ReadLines(@"C:\conf\config.txt")
    .ToDictionary(line => line.Substring(0, line.IndexOf('=')).Trim(),
                  line => line.Substring(line.IndexOf('=') + 1).Trim().Trim('"'));

  ...

  String testUrl = MySettings[var_name];

但是,如果您更喜欢&#34;变量&#34;你可以尝试ExpandoObject

  dynamic ExpSettings = new ExpandoObject();

  var expandoDic = (IDictionary<string, object>) ExpSettings;

  foreach (var pair in MySettings)
    expandoDic.Add(pair.Key, pair.Value);

  ...

  String testUrl = ExpSettings.var_name;

答案 1 :(得分:0)

我使用c#中的Json反序列化/序列化来存储和加载数据(或变量)。

这是Serialiazation:我创建了一个对象(postlist是一个对象列表),我希望将其保存在文本文件中这样:

 private void save_file()
    {
        string path = Directory.GetCurrentDirectory() + @"\list.txt";
        string json = JsonConvert.SerializeObject(postlist);
        File.WriteAllText(path, json);
        Application.Exit();
    }

您需要安装Newtonsoft.Json:http://www.newtonsoft.com/json 你可以用Nuget工具控制台做到这一点。 不要忘记使用:

using Newtonsoft.Json;

以下是从文本文件中获取所有数据的方法,这是反序列化:

private void read_file_list()
    {
        string line;

        try
        {
            using (StreamReader sr = new StreamReader("list.txt"))
            {
                line = sr.ReadToEnd();
            }
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
            jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
            postlist = JsonConvert.DeserializeObject<List<Post>>(line, jsonSerializerSettings);
        }
        catch 
        {
           // catch your exception if you want
        }
    }

以下是我将所有文字存储在对象列表中的方式&#34; postlist&#34;。

Newtonsoft非常实用且易于使用,我主要用它来从api获取数据。

这是我的第一个答案,我希望它会对你有所帮助。