tags:

views:

134

answers:

3

okay, so i have a text file with example content below

line1with some random stuff here
line 2 with something very completely different
line3 has some other neat stuff
line4 is the last line in the textfile

i need to get that text file, delete one line, and leave the REST of the file in tact. and so if i wanted to delete line 2, id want a result like this:

line1with some random stuff here
line3 has some other neat stuff
line4 is the last line in the textfile

notice i dont want any space left between the lines.

~code examples please! and even if that is impossible, any help would be appreciated! :)

+2  A: 

Assuming you had a lineIsGood method which determined whether a given line was one you wanted to keep (in your case you could just check to see if it wasn't the second line, but I'm assuming you'd want more robust criteria eventually):

Queue<string> stringQueue = new Queue<string();
string tempLine = "";

StreamReader reader = new StreamReader(inputFileName);
do
{
     tempLine = reader.ReadLine();
     if (lineIsGood(tempLine))
     {
          stringQueue.Enqueue(tempLine);
     }
}   
while(reader.Peek() != -1);
reader.Close();

StreamWriter writer = new StreamWriter(inputFileName);     
do
{
    tempLine = (string) stringQueue.Dequeue();
    writer.WriteLine(tempLine);        
}
while (stringQueue.Count != 0);
writer.Close();
Raul Agrait
This will append the lines without clearing the file. You need to write to a temporary file, then replace the original file with it.
SLaks
Does having a reader and writer on the same file really work? I wouldn't've expected it to.
Tinister
I haven't tried it, but I think that it will work since they're not on the same stream. However, as I noted above, it won't do what he wants.
SLaks
Would the reader then never reach the end of the file because the writer is appending to the file at the same rate it's being read? This seems really nasty.
Tinister
I hadn't thought of that; you have a point.
SLaks
+5  A: 

The simplest way to do it is like this:

string filePath = ...
List<string> lines = new List<string>(File.ReadAllLines(filePath ));
lines.RemoveAt(2);  //Remove the third line; the index is 0 based
File.WriteAllLines(filePath, lines.ToArray());

Note that this will be very inefficient for large files.

SLaks
A: 

maybe use the StreamWriter.Write(char[] buffer, int index, int count) overload.

It has the advantage of being able to start writing at a point in the file. So all you need to do is read in the lines and count the characters you passed, read in the line you want to change, get its length and then use it like so

StreamWriter.Write(NewLine.CharArray(),CharCount,LineLength)

TerrorAustralis