简体   繁体   中英

C# Search txt file for missing text and if missing add text

I have combined the content of three txt-files into one and now have to do the final touch. I have managed to search for a comma and changed it to a dot. So far so good. But...

Every now and then a line in that combined file reads "LENGTH " (Yes it is the word length followed by a space-character)

Sometimes that line is followed by a number... But... If that line is NOT followed by any number or other character at all it should be added the digit 0 (zero).

How do I solve this?

Read all lines of the file, raplace the wrong ones and write them back to the file:

string[] lines = File.ReadAllLines(filePath);
File.Delete(filePath);
File.WriteAllLines(filePath, lines.Select(l => l == "LENGTH " ? "LENGTH 0" : l));

You can simply stream the file line by line and replace the lines reading LENGTH with LENGTH 0 :

string source = ...; // your file's name
string target = ...; // your target file's name

File.WriteAllLines(target, File.ReadAllLines(source).Select(l => l == "LENGTH " ? "LENGTH 0" : l));

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