【问题标题】:C# reading variables into static string from text fileC#从文本文件中将变量读入静态字符串
【发布时间】:2013-03-28 14:44:54
【问题描述】:

我看过几篇文章给出了如何从文本文件中读取的示例,以及如何将字符串设为“public”(静态或 const)的示例,但我无法将两者结合在一个“函数”中' 以一种对我来说有意义的方式。

我有一个名为“MyConfig.txt”的文本文件。 其中,我有 2 行。

 MyPathOne=C:\TestOne
 MyPathTwo=C:\TestTwo

我希望能够在我启动表单时读取该文件,从而使 My​​PathOne 和 MyPathTwo 都可以从表单内的任何位置访问,使用类似这样的东西:

ReadConfig("MyConfig.txt");

我现在尝试这样做的方式是这样的,但这是行不通的:

public voice ReadConfig(string txtFile)
{
    using (StreamReader sr = new StreamResder(txtFile))
    {
        string line;
        while ((line = sr.ReadLine()) !=null)
        {
            var dict = File.ReadAllLines(txtFile)
                           .Select(l => l.Split(new[] { '=' }))
                           .ToDictionary( s => s[0].Trim(), s => s[1].Trim());
        }
        public const string MyPath1 = dic["MyPathOne"];
        public const string MyPath2 = dic["MyPathTwo"];
    }
}

txt 文件可能永远不会超过 5 或 6 行,而且我不会坚持使用 StreamReader 或字典。

只要我可以从任何地方按名称访问路径变量,并且不会添加 400 行代码之类的东西,那么我可以做任何最好、最安全、最快、最简单的事情。

我读过很多帖子,人们说数据应该存储在 XML 中,但我认为这部分实际上并不重要,因为读取文件和获取变量部分几乎都是一样的。除此之外,我宁愿能够使用某人(最终用户)无需理解 XML 即可编辑的纯 txt 文件。 (这当然意味着对空行进行大量检查,路径是否存在等等......我可以做这部分,只是想让这部分先工作)。

我已经阅读了有关将 ReadAllLines 用于数组的不同方法,有人说要创建一个新的单独的“类”文件(我还不太了解……但正在研究它)。主要是我想找到一种“稳定”的方式来做到这一点。 (项目使用的是.Net4和Linq)

谢谢!!

【问题讨论】:

  • 你是否有可能有一个类和一个数组或列表来保存文本文件中的行。然后,您可以创建一个可从任何地方访问的单例对象。当你实例化单例对象时读取文件。 - msdn.microsoft.com/en-us/library/ff650316.aspx
  • 您当前的代码有什么问题?

标签: c# global-variables text-files


【解决方案1】:

您提供的代码甚至无法编译。相反,你可以试试这个:

public string MyPath1;
public string MyPath2;

public void ReadConfig(string txtFile)
{
    using (StreamReader sr = new StreamReader(txtFile))
    {
        // Declare the dictionary outside the loop:
        var dict = new Dictionary<string, string>();

        // (This loop reads every line until EOF or the first blank line.)
        string line;
        while (!string.IsNullOrEmpty((line = sr.ReadLine())))
        {
            // Split each line around '=':
            var tmp = line.Split(new[] { '=' }, 
                                 StringSplitOptions.RemoveEmptyEntries);
            // Add the key-value pair to the dictionary:
            dict[tmp[0]] = dict[tmp[1]];
        }

        // Assign the values that you need:
        MyPath1 = dict["MyPathOne"];
        MyPath2 = dict["MyPathTwo"];
    }
}

考虑到:

  1. 您不能在方法中声明公共字段。

  2. 您无法在运行时初始化 const 字段。相反,您在编译时为它们提供一个常量值。

【讨论】:

  • 谢谢!如果我想添加 MyPath3 并使之类的东西 MyPath3 = MyPath1+@"\Test" 并且能够引用它,我也会在最顶部定义它(这会起作用还是我会使用某种'combine '声明?)?
【解决方案2】:

知道了。谢谢!

            public static string Path1;
            public static string Path2;
            public static string Path3;

            public void ReadConfig(string txtFile)
            {
                using (StreamReader sr = new StreamReader(txtFile))
                {
                var dict = new Dictionary<string, string>();
                string line;
                while (!string.IsNullOrEmpty((line = sr.ReadLine())))
                {
                            dict = File.ReadAllLines(txtFile)
                           .Select(l => l.Split(new[] { '=' }))
                           .ToDictionary( s => s[0].Trim(), s => s[1].Trim());
                }
                Path1 = dict["PathOne"];
                Path2 = dict["PathTwo"];
                Path3 = Path1 + @"\Test";
                }
            }

【讨论】:

    【解决方案3】:

    您需要在函数外部定义变量,以便其他函数可以访问它们。

    public string MyPath1; // (Put these at the top of the class.)
    public string MyPath2;
    
    public voice ReadConfig(string txtFile)
    {
        var dict = File.ReadAllLines(txtFile)
                       .Select(l => l.Split(new[] { '=' }))
                       .ToDictionary( s => s[0].Trim(), s => s[1].Trim());  // read the entire file into a dictionary.
    
        MyPath1 = dict["MyPathOne"];
        MyPath2 = dict["MyPathTwo"];
    }
    

    【讨论】:

      【解决方案4】:

      这个问题类似于Get parameters out of text file

      (我把答案放在那里。我“不能”把它贴在这里。)

      (不确定我是否应该将此问题“标记”为重复。“标记”“关闭”。)

      (重复的问题会合并吗?每个问题在 [通常是蹩脚的] 问题的措辞或 [影响力不足和力过大的] 答案中都有优点。合并后的版本可能是最好的,但合并很少是微不足道的。 )

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-29
        • 2021-04-16
        • 2021-06-04
        • 1970-01-01
        • 1970-01-01
        • 2012-11-13
        • 1970-01-01
        • 2012-01-11
        相关资源
        最近更新 更多