Search code examples
c#winformsduplicatesworkflow-foundation

C# How to duplicate line in text file (.txt) when button is clicked?


I've a winform application and I want to ducplicate a line in a text file (.txt) when I click a button. eg : Hello world

and I want to have something like:

Hello world

Hello world

when I click a button.

void duplicateLine(string text, int line){
//Read text file
//duplicate the line
//insert (Write) the duplicate line in text file(.txt)
}

Solution

  • One way to duplicate a line in a text file in C# is to use the File.ReadAllLines method to read the file into a string array, then use a loop to insert the duplicate line at the desired index, and then use the File.WriteAllLines method to write the modified array back to the file. For example, the following code snippet duplicates the first line of a text file:

    void duplicateLine(string text, int line)
    {
        //Read the file into a string array
        string[] lines = File.ReadAllLines("textfile.txt");
        
        //Create a list to store the modified lines
        List<string> newLines = new List<string>();
        
        //Loop through the array and insert the duplicate line
        for (int i = 0; i < lines.Length; i++)
        {
            //Add the original line to the list
            newLines.Add(lines[i]);
        
            //If the line is the one to be duplicated, add it again
            if (i == line)
            {
                newLines.Add(lines[i]);
            }
        }
        
        //Write the modified list back to the file
        File.WriteAllLines("textfile.txt", newLines);
    }
    

    This code will result in a text file like this:

    Hello world
    Hello world
    Some other line
    Another line