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

50 Views Asked by At

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)
}
2

There are 2 best solutions below

1
Malak Sedarous On BEST ANSWER

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
1
Hossein Sabziani On

It is better to write the code yourself and ask questions about the code problems. Try the following method:

1-Read all line of file to list using File.ReadAllLines

2- check line if not exist in the file

3-Add a new line at a specific position of list( duplicate one line)

4-Write list to file

void duplicateLine(string text, int line){

    string _path = "data.txt";  //path of your file
    var txtLines = File.ReadAllLines(_path).ToList();  //1 

    if(line>=txtLines.Count) //2
    {
        MessageBox.Show("this line not exist in file..");
        return;
    }
    txtLines.Insert(line, Text);  //3
    File.WriteAllLines(_path, txtLines); //4
}