如何从文本文件中读取KeyPair值并将其添加到Dictionary中?

时间:2017-01-26 22:40:59

标签: c#

下面是可行的,但我想从外部文件中调用所有KeyValuePair。从外部文本文件中逐行读取KeyValuePair的最佳方法是什么?我想将外部文件放在Visual Studio的App_Data文件夹中。

Dictionary<string, string> values = new Dictionary<string, string>() {

       { "TitleOne", "ABC"},
       { "TitleTwo", "FGD"},
       { "TitleThree", "NKL"},
       { "TitleFour", "WER"},
}

1 个答案:

答案 0 :(得分:1)

像这样:

Dictionary<String,String> dict = new Dictionary<String,String>();
using( StreamReader rdr = new StreamReader( File.Open("filename.txt") ) ) {

    String line;
    while( (line = rdr.ReadLine()) != null ) {

        // assuming that values are not surrounded in quotes and are separated by a space character:

        Int32 spaceIdx = line.IndexOf(' ');
        if( spaceIdx == 0 || spaceIdx == -1 ) continue; // skip invalid lines

        String key   = line.Substring( 0, spaceIdx - 1 );
        String value = line.Substring( spaceIdx );

        dict.Add( key, value );
    }
}

如果您的密钥中包含空格,则需要使用简单的解析器(例如简单的状态机读取器或正则表达式)。

由于我的代码仅拆分第一个空格字符,因此无需调用String.Split,因为value部分中的空格将丢失 - 并且您需要额外的内存和运行时成本分配新的子串。