Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i extract specific data from a file?

Tags:

c#

I have a file which has temperature data in it . I need to extract temperature from it and save the result with only temperatures in a new file.

This is the contents of the file :

BCAST:000D6F00017620E9, 02=34.23
BCAST:000D6F00017620E9, 02=12.3
BCAST:000D6F00017620E9, 02=54.01
BCAST:000D6F00017620E9, 02=12.34
BCAST:000D6F00017620E9, 02=16.22

Need to extract the data after every = i.e 34.23,12.3,54.01 etc

I have tried using sub string but it can be used when i read the file as a string and it just makes a substring of first line , rest remains same.Following is my code.Please suggest !

string temp2 = System.IO.File.ReadAllText(@"C:********\temperature.txt");
int c = temp2.IndexOf("=");
string temp3 = temp2.Substring(c + 1);
System.IO.File.WriteAllText(@"C:\*******\temperature2.txt",temp3);

Output of this code is :

34.23
BCAST:000D6F00017620E9, 02=12
BCAST:000D6F00017620E9, 02=54
BCAST:000D6F00017620E9, 02=12
BCAST:000D6F00017620E9, 02=16
like image 998
user1344602 Avatar asked Feb 21 '23 18:02

user1344602


2 Answers

ReadAllText will return the entire file as one string. It would make more sense to loop on an array of lines and use your substring code on each line.

EDIT ReadAllLines is a static call:

string[] lines = System.IO.File.ReadAllLines(fileName);

Or, read one line at a time with a stream:

var sr = new StreamReader(fileStream);
while (!sr.EndOfStream)
{
  var line = sr.ReadLine();
  // .. per line sub string
}

EDIT 2 I worked out a complete solution (note I prefer stream reading as opposed to read-all styles - it is more efficient for very large files - so it's a good practice to get used to)

var sb = new StringBuilder();

using (var file = new FileStream("C:/tmp/temps.txt", FileMode.Open, FileAccess.Read))
{
  var sr = new StreamReader(file);

  while (!sr.EndOfStream)
  {
    var nextLine = sr.ReadLine();
    int indexOfEqualSign = nextLine.IndexOf("=");

    if (indexOfEqualSign == -1 || indexOfEqualSign == nextLine.Length)
      continue;

    string rightHandSide = nextLine.Substring(indexOfEqualSign + 1);
    sb.AppendLine(rightHandSide);
  }
}

File.WriteAllText("C:/tmp/temps2.txt", sb.ToString());
like image 83
payo Avatar answered Feb 23 '23 06:02

payo


You're on the right track, but you need to loop through the lines in the file and then do a split on the =:

string[] lines = File.ReadAllLines(@"C:\********\temperature.txt"); 
StringBuilder temperatures = new StringBuilder();

foreach (string line in lines)
{
    string[] parts = line.Split('=');

    if (lines.Length > 1)
    {
        tempatures.Append(lines[1]));
        tempatures.Append("\n");
    }
}

File.WriteAllText(@"C:\*******\temperature2.txt", tempatures.ToString());
like image 20
Tim Avatar answered Feb 23 '23 07:02

Tim