Extracting data from text file

大城市里の小女人 提交于 2019-12-10 12:27:45

问题


I have a text file that starts like this:

[Details]
Version=100
Switch=340
Video=800
Date=20100912
Length=00:49:34.2
Days=1
hours=20

Is there a way that I can check each line within the [Details] section and then do something like this?

if(line == "version")
{
   // read the int 100
}

Also there is other text in the text file that is of no interest to me. I only need to find the [Details] part.


回答1:


        using (StreamReader sr = new StreamReader(path)) 
        {
            while (sr.Peek() >= 0) 
            {
                var keyPair =  sr.ReadLine();
                var key = keyPair.Split('=')[0];
                var value = keyPair.Split('=')[1];
            }
        }



回答2:


You can use File.ReadAllLines to find the lines with Version, then parse the int from there

foreach (var line in File.ReadAllLines("file").Where(line => line.StartsWith("Version")))
{
    int value = 0;
    if (int.TryParse(line.Replace("Version=","").Trim(), out value))
    {
        // do somthing with value
    }
}

Or if the file just contains 1 line with Version

string version = File.ReadAllLines("file").FirstOrDefault(line => line.StartsWith("Version="));

int value = 0;
if (int.TryParse(version.Replace("Version=", "").Trim(), out value))
{
    // do somthing with value
}   


来源:https://stackoverflow.com/questions/15213401/extracting-data-from-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!