简体   繁体   中英

How to add text to the line that starts with “hello” in a file

I have a file that contains many lines. There is a line here looking like below:

hello jim jack nina richi sam

I need to add a specific text salmon in this line and change it to below (it could be added anywhere in this line -end -begining - in the middle -doesnt matter ):

hello jim jack nina richi sam salmon

I tried:

    string path = @"C:\testFolder\newTestLog.txt";
        StreamReader myReader = new StreamReader(path);
        string[] allLines = File.ReadAllLines(path);
            foreach (string element in allLines) {
            if (element.StartsWith("hello"))
            {
                Console.WriteLine(element);
            }
        }
        myReader.Close();

    }

Using this I'm able to read the file line by line and add each line to an array and print that line if that starts with "hello", but I'm not sure how to add text to this line

Try this:

string path = @"C:\testFolder\newTestLog.txt";
var lines = File.ReadLines(path).Select(l => l + l.StartsWith("hello")?" salmon":"");
foreach (string line in lines)
    Console.WriteLine(line);

Note that this still only writes the results to the Console, as your sample does. It's not clear what you really want to happen with the output.

If you want this saved to the original file, you've opened up a small can of worms. Think of all of the data in your file as if it's stored in one contiguous block 1 . If you append text to any line in the file, that text has nowhere to go but to overwrite the beginning of the next. As a practical matter, if you need to modify file, this often means either writing out a whole new file, and then deleting/renaming when done, or alternatively keeping the whole file in memory and writing it all from start to finish.

Using the 2nd approach, where we keep everything in memory, you can do this:

string path = @"C:\testFolder\newTestLog.txt";
var lines = File.ReadAllLines(path).Select(l => l + l.StartsWith("hello")?" salmon":"");
File.WriteAllLines(path, lines);

1 In fact, a file may be split into several fragments on the disk, but even so, each fragment is presented to your program as part of a single whole.

You should use what Joel answered it's nicer but if you're having trouble implementing it try this. After adding the salmon to the lines that start with hello you can overwrite the txt file by using File.WriteAllLines

string filePath = @"C:\testFolder\newTestLog.txt";

string[] allLines = File.ReadAllLines(filePath);

for(int i = 0; i < allLines.Length; i++)
{
    if (allLines[i].StartsWith("hello"))
    {
        allLines[i] += " salmon";
    }
}

File.WriteAllLines(filePath, allLines);

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