Managing a text file in C#
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 rand开发者_C百科om 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! :)
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.
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();
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)
精彩评论