Delete last 3 lines within while ((line = r.ReadLine()) != null) but not open a new text file to delete the lines?
Posted
by
user1473672
on Stack Overflow
See other posts from Stack Overflow
or by user1473672
Published on 2012-07-03T09:03:40Z
Indexed on
2012/07/03
9:15 UTC
Read the original article
Hit count: 172
This is the code I've seen so far to delete last 3 lines in a text file, but it's required to determine string[] lines = File.ReadAllLines(); which is nt necessary for me to do so.
string[] lines = File.ReadAllLines(@"C:\\Users.txt");
StringBuilder sb = new StringBuilder();
int count = lines.Length - 3; // except last 3 lines
for (int s = 0; s < count; s++)
{
sb.AppendLine(lines[s]);
}
The code works well, but I don't wanna re-read the file as I've mentioned the streamreader above :
using (StreamReader r = new StreamReader(@"C:\\Users.txt"))
Im new to C#, as far as I know, after using streamreader, and if I wanna modify the lines, I have to use this :
while ((line = r.ReadLine()) != null)
{
#sample codes inside the bracket
line = line.Replace("|", "");
line = line.Replace("MY30", "");
line = line.Replace("E", "");
}
So, is there any way to delete the last 3 lines in the file within the "while ((line = r.ReadLine()) != null)" ??
I have to delete lines, replace lines and a few more modications in one shot, so I can't keep opening/reading the same text file again and again to modify the lines. I hope the way I ask is understable for you guys >.<
Plz help me, I know the question sounds simple but I've searched so many ways to solve it but failed =(
So far, my code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication11
{
public class Read
{
static void Main(string[] args)
{
string tempFile = Path.GetTempFileName();
using (StreamReader r = new StreamReader(@"C:\\Users\SAP Report.txt"))
{
using (StreamWriter sw = new StreamWrite (@"C:\\Users\output2.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
line = line.Replace("|", "");
line = line.Replace("MY30", "");
line = line.Replace("E", "");
line = System.Text.RegularExpressions.Regex.Replace(line, @"\s{2,}", " ");
sw.WriteLine(line);
}
}
}
}
}
}
Now my next task is to delete the last 3 lines in the file after these codes, and I need help on this one.
Thank you.
© Stack Overflow or respective owner