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" <ad@wfes.tcc.edu.tw> wrote in message
news:OS*************@TK2MSFTNGP12.phx.gbl...
Thanks,
How could I open a file, and read the content line by line?
Could you give me an example?
"Jon Skeet [C# MVP]" <sk***@pobox.com>
???????:MP************************@msnews.microsof t.com... ad <ad@wfes.tcc.edu.tw> wrote: > I want to delete some text which begin with <!DOCTYPE and end with > in a > file.
> How can I do it?
You'll need to rewrite the file. You could do it by reading from the
original file, writing (as you go) everything you *do* want to a new
file, and then moving it over the top of the old one. Alternatively you
could read the whole of the old file into memory, then write out just
the bits you want over the top of the old file.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too