Pearl Princess
Pearl Princess

Reputation: 3

how to delete a line from text file that is saved inside a string variable

I have:

String yourName = "bob";

Now I want to delete bob from the textfile. How would I do this?

using (StreamReader reader = new StreamReader("C:\\input"))
                        {
                            using (StreamWriter writer = new StreamWriter("C:\\output"))
                            {
                                while ((line = reader.ReadLine()) != null)
                                {
                                    if (String.Compare(line, yourName) == 0)
                                        continue;

                                    writer.WriteLine(line);
                                }
                            }
                        }

ive looked on this website as well as YouTube but nothing is there.

Is this possible?

Upvotes: 0

Views: 66

Answers (3)

Michael Ikechi
Michael Ikechi

Reputation: 1

Does the value of line have to be exactly equal to the yourName string?

If your target is lines that contain the yourName string, then

if (line.Contains(yourName)) continue;

should suffice.

If however, you are looking to omit lines that are exactly the same as yourName, then

if (line?.ToLowerCase() == yourName?.ToLowerCase()) continue;

should be enough.

Upvotes: 0

NullDev
NullDev

Reputation: 7321

This is possible. You need to loop through the lines and check if the current one contains your string.
Here's an example of doing that:

string yourName = "bob";
string oldLine;
string newLine = null;
StreamReader sr = File.OpenText("C:\\input");
while ((oldLine = sr.ReadLine()) != null){
    if (!oldLine.Contains(yourName)) newLine += oldLine + Environment.NewLine;  
}
sr.Close();
File.WriteAllText("C:\\output", newLine);

Note: This will delete all lines containing the word bob
Also, if you want to write to the same file, just use your input file instead of output at

File.WriteAllText("C:\\output", newLine);

I hope that helped!

Upvotes: 0

Sean Stayns
Sean Stayns

Reputation: 4244

You should use the replace method:

using (StreamReader reader = new StreamReader("C:\\input"))
                    {
                        using (StreamWriter writer = new StreamWriter("C:\\output"))
                        {
                            while ((line = reader.ReadLine()) != null)
                            {
                                // if (String.Compare(line, yourName) == 0)
                                //    continue;

                                writer.WriteLine(line.Replace(yourName, "");
                            }
                        }
                    }

If the name is in the line, then it would be replaced with "" and you have deleted it. If the name is not in the line, then the replace method return the whole unchanged line.

Show this link for more informations.

Upvotes: 1

Related Questions