Tuesday, 17 September 2013

Modify File Contents based on starting element/string

Modify File Contents based on starting element/string

I have a HL7 File like:
MSH|^~\&|ABC|000|ABC|ABC|0000||ABC|000|A|00
PID|1|000|||ABC||000|A||||||||||
PV1|1|O||||||||||||||||||||||||||||||||||||||||||
OBR|1|||00||00|00|||||||||||ABC|00|0|0||||A|||||00||ABC|7ABC||ABC
OBX|1|ABC|ABC|1|SGVsbG8=
OBX|2|ABC|ABC|1|XYTA
OBX|3|ABC|ABC|1|UYYA
I have to read only OBX segments and get the text after 5th pipe (|).
Currently I am doing this with:
StreamReader reader = new
StreamReader(@"C:\Users\vemarajs\Desktop\HL7\Ministry\HSHS.txt");
string strTest = reader.ReadToEnd();
string OBX1 = strTest.Split('\n')[3];
File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\OBX.txt", OBX1 +
Environment.NewLine);
List<string> list = new List<string>();
using (reader)
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
if (line.StartsWith("OBX|") == true)
{
string txt = line.Split('|')[5];
File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\test.txt",
txt+Environment.NewLine);
}
else
{
//string x = line + Environment.NewLine + OBX1.Distinct();
File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\newtest.txt",
line + Environment.NewLine);
File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\OBX.txt",
OBX1.Distinct().ToList() + Environment.NewLine);
}
This extracts the contents of each OBX segment at element 5 (after 5
pipes) and writes out a file called test.text, in my else statement I am
trying to modify the original HL7 file by deleting OBX|2 and OBX|3 to have
only One OBX|1 as we expect the number of OBX segments inside the HL7 file
to reach 40 or more and we don't wan't to keep those many while returning
the message to its messagebox.
My current code is trying to do this, but adds OBX|1 for each segment that
is not starting with OBX| (this is due my logic), how do I avoid this ?

No comments:

Post a Comment