ad,
Before I start: Code disclaimer: The code below overwrites/deletes data. I
have not tested it. It is purely meant as an example, and no warrenties are
either expressed or implied. No usefulness statement is made. Use at your
own risk.
One approach would be to read line by line as you mentioned:
string filepath = "myfilename.txt";
string newFilePath = "myNewFile.txt";
using (TextWriter writer = File.CreateText(newFilePath))
{
using (TextReader reader = File.OpenText(filenpath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// do whatever with the "line" to delete or add stuff
writer.WriteLine(line);
}
reader.Close();
}
writer.Close();
}
File.Delete(filepath);
File.Move(newFilePath, filepath);
A better approach might be to read the entire file into a string, manipulate
that string, and then write the whole string back. For example:
string filepath = "myfilename.txt";
string fileContents;
using (TextReader reader = File.OpenText(filepath))
{
fileContents = reader.ReadToEnd();
reader.Close();
}
// use fileContents.Replace() or other string manipulation to fix the file
using (TextWriter writer = File.CreateText(filepath))
{
writer.Write(fileContents);
writer.Close();
}
Also note, I have not checked to see if the file exists
(File.Exists(filename)) or done any other error checking. This is just an
example for you to get started with.
Hope this helps...
--
Frisky
Intellectuals solve problems; geniuses prevent them. ~ Albert Einstein
ad said:
Thanks,
How could I open a file, and read the content line by line?
Could you give me an example?