Parsing a file into separate strings - c#

File consist of 2 line of text.
need to parse the file so that each line of text is assigned to a string. my string variables are "PhoneNumber" and "Location" and the incoming file is stored in string "line".
using (var sr = new StreamReader(incoming))
{
while ((line = sr.ReadLine()) != null)
{
PhoneNumber = ??
Location = ??
}
}

Maybe something like this?
using System.IO;
string Phonenumber = "";
string Location = "";
string[] filecontent = File.ReadAllLines("Filepath");
if (filecontent.Length > 0)
Phonenumber = filecontent[0];
if (filecontent.Length > 1)
Location = filecontent[1];
Edit:
Option 2 using StreamReader:
string Phonenumber = "";
string Location = "";
int LineCount = 0;
using (var sr = new StreamReader(#"Path"))
{
var linecontent = "";
while ((linecontent = sr.ReadLine()) != null)
{
if (LineCount == 0)
Phonenumber = linecontent;
if (LineCount == 1)
Location = linecontent;
LineCount++;
}
}
Option 3 also using StreamReader:
using (var sr = new StreamReader(#"Path"))
{
string Phonenumber = "";
string Location = "";
string[] filecontent = sr.ReadToEnd().Split("\n"); //Read text from file and split it into single lines
if (filecontent.Length > 0)
Phonenumber = filecontent[0];
if (filecontent.Length > 1)
Location = filecontent[1];
}

Related

How to read serial number from text file

I have a text file which contain of lots of information, but i only want to show the serial number of the text file. I am able to read and show the whole line of the serial number in label, but i only required the serial number in the format of ["BcXXXXX"]. Anyone would able to guide through?
string path = #"D:\Sample.txt";
StringBuilder buffer = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
String str = sr.ReadLine();
if (Regex.IsMatch(str, "Bc"))
buffer.Append(str);
string s = buffer.Append(str);
int start = s.IndexOf("["Bc") + 1;
int end = s.IndexOf(""]" , start);
string result = s.Substring(start, end - start);
label2.Text = result.ToString();
}
string serialNumber = System.IO.File.ReadLines(#"D:\Sample.txt")
.Select(line =>
{
var match = System.Text.RegularExpressions.Regex.Match(line, #"^\[""(.*)""\]$");
return match.Success ? match.Groups[1].Value : null;
}).FirstOrDefault(sn => sn != null);

Comparing rows in a csv file

I am currently using the below code to compare two csv files with each other. This code gives an output with all the rows that are not the same. But when a row is missing everything after that row is not the same. How can I fix this? Thanks in advance.
List<string> lines = new List<string>();
List<string> lines2 = new List<string>();
try
{
StreamReader reader = new StreamReader(System.IO.File.OpenRead(file1));
StreamReader read = new StreamReader(System.IO.File.OpenRead(file2));
List<string> differences = new List<string>();
string line;
string line2;
int i = 0;
while ((line = reader.ReadLine()) != null && (line2 = read.ReadLine()) != null)
{
string[] split = line.Split(Convert.ToChar("\t"));
string[] split2 = line2.Split(Convert.ToChar("\t"));
if (split[i] != split2[i])
{
differences.Add("this row is not the same:, " + line);
}
else
{
}
i++;
}
System.IO.File.WriteAllLines(differencesFile, differences);
reader.Dispose();
read.Dispose();
}
catch
{
}
After help from a friend I made it work with this code:
List<string> file1 = new List<string>();
List<string> output = new List<string>();
string differencesFile = path;
File.WriteAllText(differencesFile, "");
try
{
StreamReader readFile1 = new StreamReader(System.IO.File.OpenRead(pathfile1));
string lineFile1;
while ((lineFile1 = readFile1.ReadLine()) != null)
{
bool match = false;
string[] colums = lineFile1.Split('\t');
StreamReader readFile2 = new StreamReader(System.IO.File.OpenRead(pathfile2));
string line2;
while ((line2 = readFile2.ReadLine()) != null)
{
string[] columsFile2 = line2.Split('\t');
if (colums[0] == columsFile2[0])
{
match = true;
}
}
if (!match)
{
output.Add(colums[0] + "; doesnt exist in pathfile2");
}
}
System.IO.File.WriteAllLines(differencesFile, output);
}
catch { }

How to edit a file, appending data at the beginning, without rewriting the whole file?

I have a csv file, and I need to add a unique ID based on the first two characters of the file. I have the following code:
using (StreamReader sr = new StreamReader(f))
{
string currentLine;
int id = 0;
while ((currentLine = sr.ReadLine()) != null)
{
string row = currentLine.ToString();
string FirstTwoCharacters = currentLine.Substring(0, 2);
if (FirstTwoCharacters == "01")
{
id = id + 1;
row += "*" + id.ToString();
using (StreamWriter files = File.AppendText(dir + newfilename))
{
files.WriteLine(row);
}
}
else
{
row += "*" + id.ToString();
using (StreamWriter files = File.AppendText(dir + newfilename))
{
files.WriteLine(row);
}
}
}
}
The csv files can be huge, 1Gb in size, around 6 million rows. Just wanted advice, if there is a quicker way to handling this, as it currently can take 3+ hours to process a file, and multiple files can be received in one go.
Instead of opening new file for appending line for each line of input file you can keep stream writer opened:
using (StreamReader sr = new StreamReader(f))
using (StreamWriter files = File.AppendText(dir + newfilename))
{
string currentLine;
int id = 0;
while ((currentLine = sr.ReadLine()) != null)
{
string firstTwoCharacters = currentLine.Substring(0, 2);
if (firstTwoCharacters == "01")
id++;
files.WriteLine(currentLine + "*" + id);
}
}
You can also use File.ReadLines to enumerate source lines:
using (StreamWriter writer = File.AppendText(dir + newfilename))
{
int id = 0;
foreach(var line in File.ReadLines(f))
{
if (line.Substring(0,2) == "01")
id++;
writer.WriteLine($"{line}*{id}");
}
}
Or even LINQ approach
int id = 0;
var newLines = from line in File.ReadLines(f)
let incrementId = line.Substring(0,2) == "01"
select $"{line}*{incrementId ? (++id) : id}";
File.WriteAllLines(dir + newfilename, newLines);
opening the (File.AppendText) inside the while loop is costly, move this to outside the while
using (StreamReader sr = new StreamReader(f))
{
string currentLine;
int id = 0;
using (StreamWriter files = File.AppendText(dir + newfilename))
{
while ((currentLine = sr.ReadLine()) != null)
{
string row = currentLine.ToString();
string FirstTwoCharacters = currentLine.Substring(0, 2);
if (FirstTwoCharacters == "01")
{
id = id + 1;
row += "*" + id.ToString();
files.WriteLine(row);
}
else
{
row += "*" + id.ToString();
files.WriteLine(row);
}
}
}
}

Unexpected "," from StreamReader to StreamWriter

I've tried a lot of things as well as research and asking friends, but can't seem to write a second line without a "," replacing the line. All I'd to do is have a single line for each item read in a separate file.
Each read file has several of these items:
2/20/2014 7:33:10 AM
OPERATOR: jason
FILE: C:\ax14\Setups\000062363106RH.prt
UNITS: english
TEST RESULT: Pass
CHANNEL 1
TEST TYPE: VELOCITY
RESULT: Pass
UPPER LIMIT: 0.2260
LOWER LIMIT: 0.2220
MAX THICKNESS: 2.0110
MIN THICKNESS: 1.0110
MEASURED VELOCITY: 0.2225
MEASURED THICKNESS: 1.5215
Id like to have the date and velocity line in one line like this:
"2/20/2014 7:33:10 AM, MEASURED VELOCITY: 0.2225"
and this is my problem
2/20/2014 7:33:10 AM,
,
,
,
,
,
,
,
,
,
,
,
, MEASURED VELOCITY: 0.2225
,
2/20/2014 7:52:28 AM,
,
,
,
,
,
,
,
,
,
,
,
, MEASURED VELOCITY: 0.2224
,
2/20/2014 7:58:46 AM,
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
namespace conApp
{
class Program
{
static void Main(string[] args)
{
String line;
try
{
using (StreamWriter sw = new StreamWriter("C:\\writetest\\writetest.txt"))
{
string mydirpath = "C:\\chat\\";
string[] txtFileList = Directory.GetFiles(mydirpath, "*.txt");
foreach (string txtName in txtFileList)
{
System.IO.StreamReader sr = new System.IO.StreamReader(txtName);
while ((line = sr.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
String spart = ".prt";
String sam = " AM";
String spm = " PM";
String sresult = "TEST RESULT: ";
String svelocity = "MEASURED VELOCITY: ";
String part = "";
String date = "";
String result = "";
String velocity = "";
// sw.WriteLine(line);
if (line.Contains(sam))
{
date = line;
}
if (line.Contains(spm))
{
date = line;
}
if (line.Contains(spart))
{
part = line;
}
if (line.Contains(sresult))
{
result = line;
}
if (line.Contains(svelocity))
{
velocity = line;
}
int I = 2;
string[] x = new string[I];
x[0] = date;
x[1] = velocity;
sw.WriteLine(x[0] + "," + x[1]);
}
}
}
}
}
catch
{
}
}
}
}
Here is my suggestion for the full Main() trying to use as much from your code as possible. Declaring your vars outside the while statement you don't need to make it null.
EDIT- I forgot you said:
Each read file has several of these items
So added a few lines to handle that.
static void Main(string[] args)
{
string line;
try
{
using (StreamWriter sw = new StreamWriter("C:\\writetest\\writetest.txt"))
{
string mydirpath = "C:\\chat\\";
string[] txtFileList = Directory.GetFiles(mydirpath, "*.txt");
foreach (string txtName in txtFileList)
{
string spart = ".prt";
string sam = " AM";
string spm = " PM";
string sresult = "TEST RESULT: ";
string svelocity = "MEASURED VELOCITY: ";
string part = string.Empty;
string date = string.Empty;
string result = string.Empty;
string velocity = string.Empty;
using (StreamReader sr = new StreamReader(txtName))
{
while ((line = sr.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line) && line.Trim().Length != 0)
{
if (line.Contains(sam) || line.Contains(spm))
{
// Every new date means a new record. If you already have data for a record, first write it.
if (date != string.Empty && velocity != string.Empty)
{
int I = 2;
string[] x = new string[I];
x[0] = date;
x[1] = velocity;
sw.WriteLine(x[0] + "," + x[1]);
}
// Then reset data to prepare it for a new record
part = string.Empty;
result = string.Empty;
velocity = string.Empty;
date = line;
}
if (line.Contains(spart))
{
part = line;
}
if (line.Contains(sresult))
{
result = line;
}
if (line.Contains(svelocity))
{
velocity = line;
}
}
}
}
// After last record you still have some data to write
if (date != string.Empty && velocity != string.Empty)
{
int I = 2;
string[] x = new string[I];
x[0] = date;
x[1] = velocity;
sw.WriteLine(x[0] + "," + x[1]);
}
}
}
}
catch
{
}
}
Only write the line once you have both values:
Then reset both values to null.
sw.WriteLine(x[0] + "," + x[1]);
Becomes:
if ( !String.IsNullOrWhitespace( date) && !String.IsNullOrWhitespace( velocity )
{
sw.WriteLine(x[0] + "," + x[1]);
date = null;
velocity = null;
}
As Blas mentioned you also need to move the variables outside the while statement:
String result = "";
String velocity = "";
while ((line = sr.ReadLine()) != null)
You can use this Regex Pattern to Achieve your goal :
(^.*?(?:AM|PM).*?)\r?\n.*(MEASURED VELOCITY:.*?$).*
And here's the code:
using (StreamWriter sw = new StreamWriter("C:\\writetest\\writetest.txt"))
{
string mydirpath = "C:\\chat\\";
string[] txtFileList = Directory.GetFiles(mydirpath, "*.txt");
Regex regex = new Regex("(^.*?(?:AM|PM).*?)\r?\n.*(MEASURED VELOCITY:.*?$).*",
RegexOptions.Multiline | RegexOptions.Singleline);
foreach (string txtName in txtFileList)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(txtName))
{
string text = sr.ReadToEnd();
sw.WriteLine(regex.Replace(text, "$1, $2"));
}
}
}
Output for given file example:
2/20/2014 7:33:10 AM, MEASURED VELOCITY: 0.2225

Open a resource file with StreamReader?

This doesnt work:
string fileContent = Resource.text;
StreamReader read = File.OpenText(fileContent);
string line;
char[] splitChar = "|".ToCharArray();
while ((line = read.ReadLine()) != null)
{
string[] split = line.Split(splitChar);
string name = split[0];
string lastname = split[1];
}
read.Dispose();
How do you open a resource file to get its contents?
Try like this:
string fileContent = Resource.text;
using (var reader = new StringReader(fileContent))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] split = line.Split('|');
string name = split[0];
string lastname = split[1];
}
}
I think the variable fileContent already has all the contents you need.
to read resources, you need a special Stream named "ResourceReader", you can use it like this :
string fileContent = "<your resource file>";
using (ResourceReader reader = new ResourceReader(fileContent))
{
foreach (IDictionaryEnumerator dict in reader)
{
string key = dict.Key as string;
object val = dict.Value;
}
}

Categories

Resources