Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading