How to delete some text in a file

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I want to delete some text which begin with <!DOCTYPE and end with > in a
file.
How can I do it?
 
ad said:
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.
 
Thanks,
How could I open a file, and read the content line by line?
Could you give me an example?
 
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?
 
ad said:
How could I open a file, and read the content line by line?
Could you give me an example?

Use StreamReader and its ReadLine method. See the docs for ReadLine for
an example, but rather than using Peek, call ReadLine until it returns
null.
 
I want to delete some text which begin with <!DOCTYPE and end with > in a
file.
How can I do it?

You cannot change the file in-place if that is what you are asking.
You will have to open the file and read through it, copying the stuff
you want to keep to a second file.

rossum



The ultimate truth is that there is no ultimate truth
 
Back
Top