简体   繁体   中英

C#: Read data from txt file

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#?

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.

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));
}

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM