简体   繁体   中英

How to delete a string from a text file?

I currently have two strings assigned - domain,subdomain

How could I delete any matched occurrences of these strings in a text file?

string domain = "127.0.0.1 test.com"
string subdomain = "127.0.0.1 sub.test.com"

I don't think using a regex would be ideal in this situation.

How can this be done?

You need to:

  • Open the existing file for input
  • Open a new file for output
  • Repeatedly:
    • Read a line of text from the input
    • See if it matches your pattern (it's unclear at the moment what pattern you're looking for)
    • If it doesn't , write the line to the output (or if you're only trying to remove bits of lines, work out which bit you want to write out)
  • Close both the input and output (a using statement will do this automatically)
  • Optionally delete the original file and rename the new one if you want to effectively replace the original.
var result = Regex.Replace(File.ReadAllText("file.txt"),
    @"127\.0\.0\.1 test\.com|127\.0\.0\.1 sub\.test\.com", string.Empty);

Then write to file obtained result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM