how to get two more lines in textfile - c#

i have following code i want this line and next 2 below lines how do this any idea. please help,i want last number please see text below.
static void Main()
{
int counter = 0; string line;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
sb.AppendLine(line.ToString());
}
}
}
Console.WriteLine(sb.ToString());
Console.ReadKey();
}
***** INCOMING CALL: 25/04/2016 - 11:45 *****
NAME: Test
NUMBER: (425) 555-1212
***** INCOMING CALL: 25/04/2016 - 11:45 *****
NAME: Test2
NUMBER: (425) 544-1213

Just call file.ReadLine two more times, but it is important to check if the returned string is null because you could reach an unexpected end of file and your code is no more protected by the check in the while condition
...
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
}
}
}
If you want to get just the last three lines (assuming that your file is well formatted) then you could add a reset of the StringBuilder inside the loop
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
// This will remove the previous data and keep
// just the last three lines.....
sb.Length = 0;
sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
}
}
}
In alternative, but I am not sure if this is a good idea from a performance point of view (in particular if we are talking of a large file), we could use linq in this way
string result = string.Join(Environment.NewLine,
File.ReadLines(#"E:\file\log.txt").Reverse().Take(3));

static void Main()
{
int counter = 0; string line;
List<string> ss = new List<string>();
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
ss.Add(line);
line = file.ReadLine();
if (line != null)
ss.Add(line);
line = file.ReadLine();
if (line != null)
ss.Add(line);
}
}
}
var item = ss.LastOrDefault();
string number = item.Substring(0, 24).Replace("NUMBER:", "").Trim();
Console.WriteLine(number);
Console.ReadKey();
}

Related

i want to delete lines from the top of the text file (Except 7000 lines from the End)

the below code deleting the particular line like: line no 12
but exactly the need is keep the last 7000 lines and delete the remaining lines from the top of the txt.
string line = null;
int line_number = 0;
int line_to_delete = 12;
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
line_number++;
if (line_number == line_to_delete)
continue;
writer.WriteLine(line);
}
}
}
Something like this maybe?
var tempFile = Path.GetTempFileName();
var linesToKeep = File.ReadLines(fileName);
// if the file is less or equal than 7000, do nothing
if(linesToKeep.Count() > 7000) {
linesToKeep = linesToKeep.Skip(linesToKeep.Count() - 7000);
File.WriteAllLines(tempFile, linesToKeep);
File.Delete(fileName);
File.Move(tempFile, fileName);
}
Of course the 7000 can be substituted by something else like a variable.
Two passes of the file for low memory footprint.
int lines_to_keep = 7_000;
string line = null;
int line_number = 0;
int lines_in_file = 0;
using (StreamReader reader = new StreamReader("C:\\input")) {
while ((line = reader.ReadLine()) != null) {
lines_in_file++;
}
}
int lines_to_discard = lines_in_file - lines_to_keep
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null && line_number < lines_to_discard) {
line_number ++
}
while ((line = reader.ReadLine()) != null) {
writer.WriteLine(line);
}
}
}

searching a line from a text with a keyword (solved) and display the third line after the searched line

i want to display the third line after searhing the initial line with a keyword from a text :
and i want to sperate all the variable in the third line in textboxs.
the keyword is [Ref 1]
{ // string motcledm = "code:A14";
string line;
string motcletest = SEARCH.Text;
using (System.IO.StreamReader file = new System.IO.StreamReader(#"D:\\TEST.txt"))
{
while ((line = file.ReadLine()) != null)
{
if ((line.Contains(motcletest)))
{
richTextBox1.Text = line.ToString();
}
}
The output i need
As you told, you have extracted the Third Line, Split on ',' to get an array of strings
String thirdLine = "F8,F9,...";
String[] strArray = thirdLine.Split(',');
foreach(string _val in strArray){
//do your stuff
}
string line;
string motcletest = SEARCH.Text;
using (System.IO.StreamReader file = new System.IO.StreamReader(#"D:\\TEST.txt"))
{
while ((line = file.ReadLine()) != null)
{
if ((line.Contains(motcletest)))
{
richTextBox1.Text = line.ToString();
file.ReadLine();//read first line after matching line
file.ReadLine();//read second line after matching line
line = file.ReadLine(); //third line that you are looking for
foreach(var value in line.Split(','))//split by ,
{
//Add the value the controls(textbox)
//if the count is not fixed, you might need to create a control and add it to a panel
}
}
}

Removing columns in CSV file using c#

I want to remove a column with a specific value. The code below is what I used to remove a row. Can I reverse this to remove a column?
int row = comboBox1.SelectedIndex;
string verw = Convert.ToString(txtChange.Text);
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(System.IO.File.OpenRead(filepath)))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(","))
{
string[] split = line.Split(',');
if (split[row] == kill)
{
//achter split vul je de rij in
}
else
{
line = string.Join(",", split);
lines.Add(line);
}
}
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string line in lines)
writer.WriteLine(line);
}
Assuming we ignore the subtleties of writing CSV, this should work:
public void RemoveColumnByIndex(string path, int index)
{
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(path))
{
var line = reader.ReadLine();
List<string> values = new List<string>();
while(line != null)
{
values.Clear();
var cols = line.Split(',');
for (int i = 0; i < cols.Length; i++)
{
if (i != index)
values.Add(cols[i]);
}
var newLine = string.Join(",", values);
lines.Add(newLine);
line = reader.ReadLine();
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (var line in lines)
{
writer.WriteLine(line);
}
}
}
The code essentially loads each line, breaks it down into columns, loops through the columns ignoring the column in question, then puts the values back together into a line.
This is an over-simplified method, of course. I am sure there are more performant ways.
To remove the column by name, here is a little modification to your code example.
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(System.IO.File.OpenRead(path)))
{
string target = "";//the name of the column to skip
int? targetPosition = null; //this will be the position of the column to remove if it is available in the csv file
string line;
List<string> collected = new List<string>();
while ((line = reader.ReadLine()) != null)
{
string[] split = line.Split(',');
collected.Clear();
//to get the position of the column to skip
for (int i = 0; i < split.Length; i++)
{
if (string.Equals(split[i], target, StringComparison.OrdinalIgnoreCase))
{
targetPosition = i;
break; //we've got what we need. exit loop
}
}
//iterate and skip the column position if exist
for (int i = 0; i < split.Length; i++)
{
if (targetPosition != null && i == targetPosition.Value) continue;
collected.Add(split[i]);
}
lines.Add(string.Join(",", collected));
}
}
using (StreamWriter writer = new StreamWriter(path, false))
{
foreach (string line in lines)
writer.WriteLine(line);
}

Deleting Lines in text files c# using writeline

I am using this code so far - it writes the file but doesn't remove the line specified.. any help would be nice...
if (textBox1.Text == "")
{
MessageBox.Show("Please select a file");
}
else
{
string line = null;
StringBuilder sb = new StringBuilder();
string lineDelete = "hi";
// Read the file and display it line by line.
using (System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text)){
using (System.IO.StreamWriter writer = new System.IO.StreamWriter("C:\\test3.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (String.Compare (line, lineDelete) == 0)
continue;
writer.WriteLine(line);
}
MessageBox.Show("Formatting Complete");
// Suspend the screen.
}
}
"It doesn't remove the line specified" is somewhat misleading, isn't it? You are writing lines from file1 to file2, lines which are "hi" will be omitted. So you are ignoring, not deleting those lines. Is that what you want? Also, note that C# is case sensitive and that there also might be special characters which you can't see directly like white-spaces.
So you could use Trim to remove white-spaces from the start and end of the line and you can use String.Equals to compare case-insensitive:
while ((line = file.ReadLine()) != null)
{
line = line.Trim();
if(line.Equals(lineDelete, StringComparison.CurrentCultureIgnoreCase));
continue;
else
writer.WriteLine(line);
}

NullReference Exception in converting string to Char array

It is showing Null Reference Exception on line char[] myChar = read.ToCharArray();.
I am unable to figure out. Please help
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("TextFile1.txt");
string read = "";
while (read != null)
{
read = myReader.ReadLine();
Console.WriteLine(read);
}
char[] myChar = read.ToCharArray();
for (int i = 0; i < myChar.Length; i++)
{
Console.WriteLine(myChar[i]);
}
Console.WriteLine(read);
myReader.Close();
Console.ReadKey();
}
}
The read should be null when the loop is finished and calling ToCharArray on null should give exception. you can put this statement in while loop. I believe you are trying to do some experimentation as you have already printed the string with Console.WriteLine(read);
while ((read = sr.ReadLine()) != null)
{
Console.WriteLine(read);
char[] myChar = read.ToCharArray();
for (int i = 0; i < myChar.Length; i++)
Console.WriteLine(myChar[i]);
}
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
sb.Append(line);
}
}
var chars = sb.ToString().ToCharArray();
However, you should add each line into a stringbuilder and then convert it into char array. The thing is what you really want to do?

Categories