将filename和headertext值保存为键值对集合

时间:2012-01-08 17:53:58

标签: c#

给出以下文本文件:

Find all "HeaderText="", Subfolders, Find Results 1, "Entire Solution"
  C:\Documents and Settings\user\My Documents\Visual Studio 2008\Projects\WebApplication1\WebApplication1\Default.aspx(16):                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" 
  C:\Documents and Settings\user\My Documents\Visual Studio 2008\Projects\WebApplication1\WebApplication1\Default.aspx(18):                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" 
  C:\Documents and Settings\user\My Documents\Visual Studio 2008\Projects\WebApplication1\WebApplication1\Default.aspx(20):                <asp:BoundField DataField="ContactName" HeaderText="ContactName" 
  Matching lines: 3    Matching files: 1    Total files searched: 5

将HeaderText的文件名和值放在集合中的最佳方法是什么?

for example,

var test = new List<KeyValuePair<string,string>>();

test.Add(Default.aspx, CustomerID);
test.Add(Default.aspx, CompanyName);
test.Add(Default.aspx, ContactName);

3 个答案:

答案 0 :(得分:1)

我建议使用NameValueCollection而不是List<KeyValuePair<string,string>>来保持你的配对。 NameValueCollection每个键可以有多个条目。

如果文件不是很大,您可以执行以下操作:

  1. 使用System.IO.File.ReadAllLines阅读文件并执行 数组中每个有效行的步骤2-4。

  2. 使用Path.GetFileName从完整路径获取文件名。

  3. 使用IndexOfSubstring解析字符串以获取 HeaderText值。

  4. 将该对添加到NameValueCollection

答案 1 :(得分:1)

另一个正则表达式解决方案,这个使用命名组:

public static List<KeyValuePair<string, string>> Process(string fileContents)
{
    const string regexPattern = @"\\(?<filename>[\w\.]+)\(.*HeaderText=""(?<headerText>\w+)""";

    var matches = Regex.Matches(fileContents, regexPattern);

    var test = new List<KeyValuePair<string, string>>();

    foreach (Match match in matches)
    {
        var fileName = match.Groups["filename"].Value;
        var headerText = match.Groups["headerText"].Value;

        test.Add(new KeyValuePair<string, string>(fileName, headerText));
    }

    return test;
}

答案 2 :(得分:0)

您可以使用正则表达式:

public IEnumerable<KeyValuePair<string, string>> Parse(StreamReader reader)
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        var tokens = Regex.Split(line, @"\(\d+\)\:");
        if (tokens.Length > 1)
        {
            var file = Path.GetFileName(tokens[0]);
            var match = Regex.Match(tokens[1], @"HeaderText=\""(\w+)\""");
            if (match.Success)
            {
                yield return new KeyValuePair<string, string>(
                    file, match.Groups[1].Value
                );
            }
        }
    }
}

可以像这样调用:

using (var reader = File.OpenText("test.txt"))
{
    foreach (var item in Parse(reader))
    {
        Console.WriteLine("file: {0}, header: {1}", item.Key, item.Value);
    }
}