Как написать в файле начиная с предпоследней строчки? - C#
Формулировка задачи:
Есть файл, в который надо записать данные, начиная с предпоследней строчки.
Это код который пишет в файл текст, в конец файла.
Подскажите пожалуйста как реализовать?
private void metroButton1_Click(object sender, EventArgs e)
{
StreamWriter write_text;
FileInfo file = new FileInfo(Application.StartupPath + @"\Data\BooksPIP.xml");
write_text = file.AppendText();
write_text.WriteLine(metroTextBox1.Text);
write_text.WriteLine(metroTextBox1.Text);
write_text.Close();
this.Hide();
}Решение задачи: «Как написать в файле начиная с предпоследней строчки?»
textual
Листинг программы
void Function() //Если последняя строчка "Каталог" то удаление
{
string[] readText = System.IO.File.ReadAllLines(Application.StartupPath + @"\Data\BooksPIP.xml", Encoding.Default);
string result = readText[readText.Length - 1];
if (result == "</catalog>")
{
ReadDeleteHashFromFile(Application.StartupPath + @"\Data\BooksPIP.xml");
}
}
private static string ReadDeleteHashFromFile(string MyFilePath) //Удаление последней строчки
{
string lastline = "";
using (StreamReader reader = new StreamReader(Application.StartupPath + @"\Data\BooksPIP.xml"))
{
using (StreamWriter writer = new StreamWriter("myfile.tmp"))
{
string line = reader.ReadLine();
while (!reader.EndOfStream)
{
writer.Write(line);
line = reader.ReadLine();
if (!reader.EndOfStream)
writer.Write(writer.NewLine);
}
lastline = line;
}
}
File.Delete(MyFilePath);
File.Move("myfile.tmp", MyFilePath);
File.Delete("myfile.tmp");
return lastline;
}