HOW DO YOU EDIT A TEXT FILE?
i cannot find this, all i want to do is make a form program that will edit a portion of text within a txt file, i have no idea how to reference the text file or what commands would be used to edit it
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Aug 25, 2007, 9:12 AM
The easiest way is to read the whole file, make the changes to the text and then write it all back, overwriting the original file. Here's an example.
Suppose you have this textfile, salfile.txt, and you want to interchange the second and fourth lines:
First
Fourth
Third
Second
This console program (.NET 2.0) should achieve this:
using System;
using System.IO;
using System.Collections.Generic;
class Test
{
static void Main()
{
string line = null; lines = new List();
List
StreamReader reader = new StreamReader("salfile.txt");
// read all the lines in the file and store them in the List
while((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
reader.Close();
// change the second line
lines[1] = "Second";
// change the fourth line
lines[3] = "Fourth";
StreamWriter writer = new StreamWriter("salfile.txt");
// write the lines back to the file, overwriting the original one
for (int i = 0; i < lines.Count; i++)
{
if (i < lines.Count - 1)
Console.WriteLine(lines[i]);
else
Console.Write(lines[i]);
}
writer.Close();
// check it worked
reader = new StreamReader("salfile.txt");
while((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
reader.Close();
Console.WriteLine("\n\nPress any key to end the program");
Console.ReadKey();
}
}