C#: Read data from txt file

ε祈祈猫儿з 提交于 2019-12-08 00:27:41

问题


I have an .EDF (text) file. The file's contents are as follows:

    ConfigFile.Sample, Software v0.32, CP Version 0.32
    [123_Float][2]
    [127_Number][0]
    [039_Code][70]

I wnat to read these items and parse them like this:

    123_Float - 2
    127_Number - 0
    039_Code - 70

How can I do this using C#?


回答1:


Well, you might start with the File.ReadAllLines() method. Then, iterate through the lines in that file, checking to see if they match a pattern. If they do, extract the necessary text and do whatever you want with it.

Here's an example that assumes you want lines in the format [(field 1)][(field 2)]:

// Or wherever your file is located
string path = @"C:\MyFile.edf";

// Pattern to check each line
Regex pattern = new Regex(@"\[([^\]]*?)\]");

// Read in lines
string[] lines = File.ReadAllLines(path);

// Iterate through lines
foreach (string line in lines)
{
   // Check if line matches your format here
   var matches = pattern.Matches(line);

   if (matches.Count == 2)
   {
      string value1 = matches[0].Groups[1].Value;
      string value2 = matches[1].Groups[1].Value;

      Console.WriteLine(string.Format("{0} - {1}", value1, value2));
   }
}

This outputs them to the console window, but you could obviously do whatever you want with value1 and value2 (write them to another file, store them in a data structure, etc).

Also, please note that regular expressions are not my strong point -- there's probably a much more elegant way to check if a line matches your pattern :)

If you want more info, check out MSDN's article on reading data from a text file as a starting point.




回答2:


Let us assume your file really is as simple as you describe it. Then you could drop the first line and parse the data lines like this:

foreach (string line in File.ReadAllLines(@"C:\MyFile.edf").Skip(1))
{
    var parts = line.Split("][");
    var value1 = parts[0].Replace("[", "");
    var value2 = parts[1].Replace("]", "");

    Console.WriteLine(string.Format("{0} - {1}", value1, value2));
}



回答3:


Another variation.

var lines = File.ReadAllLines(file)
    .Skip(1)
    .Select(x => x.Split(new[] { '[', ']' }, 
        StringSplitOptions.RemoveEmptyEntries));
foreach(var pair in lines)
{
    Console.WriteLine(pair.First()+" - "+pair.Last());
}


来源:https://stackoverflow.com/questions/4195540/c-read-data-from-txt-file

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