如何使用键值对从文件中获取字符串?

时间:2017-01-02 08:40:12

标签: c# .net

我这里有文件是文件的内容:

# Web surround localized strings
# English language
#
# Important: This file must be saved with UTF-8 encoding
#

# General

# GeoMarker - temporary pin markup.
SERVERERROR             = Error!Please Contact admin.
ERRORSTACKTRACE         = Stack Trace

我需要根据密钥从上面的文件中获得按摩。目前我在SERVERERRORERRORSTACKTRACE上面的文件中我需要根据按键获取massege。

如何在c#中实现它?

2 个答案:

答案 0 :(得分:1)

int counter = 0;
string line;
System.IO.StreamReader file =
            new System.IO.StreamReader("s.txt");
while((line = file.ReadLine()) != null)
{
if(line.Contains("SERVERERROR") || line.Contains("ERRORSTACKTRACE") )
    Console.WriteLine (line);
    counter++;
}
    file.Close();

输出:

SERVERERROR =错误!请联系管理员。 ERRORSTACKTRACE =堆栈跟踪

此外,为了得到确切的错误:

...

if(line.Contains("SERVERERROR") || line.Contains("ERRORSTACKTRACE") )

Console.WriteLine (line.Split('=')[1].ToString());

...

答案 1 :(得分:1)

以下作品:

var str = "SERVERERROR             = Error!Please Contact admin."+
                "ERRORSTACKTRACE         = Stack Trace";

    var output = new Dictionary<string,string>();

    foreach(var item in str.Split('.').ToList()){
        var kv = item.Split('=');
        output.Add(kv[0].Trim(),kv[1].Trim());
    }

    Console.WriteLine(output["SERVERERROR"]);
    Console.WriteLine(output["ERRORSTACKTRACE"]);

检查这个小提琴:     https://dotnetfiddle.net/5LgiE7