Click here to Skip to main content
14,735,210 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends,
How to append a files in the C#.net? I have a Input Folder and 4 txt files in the Input Folder. i want to merge/Append a files in the same folder and Appended files will delete after appending .

Folder name: Test
File Names are
1) 2012_03_05_05:50:30.txt
2) 2012_03_05_05:50:35.txt
3 ) 2012_03_05_05:50:40.txt
4 ) 2012_03_05_05:50:45.txt. here there are 4 files in the Test Folder . I want to append a files into 1st file and Automatically. 2nd,3rd,4th file should be deleted after Appending or merge a files .How can i achieve this?
Posted
Comments
Chandrakantt 5-Mar-12 7:51am
   
You will not be able to create a file which has ":" in its name

you can use below code which takes 4 files and create a single file after appending all data of all files.

static void Main(string[] args)
{
     string[] Filename = new string[4] {@"F:\Test\2012_03_05_055030.txt", @"F:\Test\2012_03_05_055035.txt",
                           @"F:\Test\2012_03_05_055040.txt", @"F:\Test\2012_03_05_055045.txt"};

     string text = System.IO.File.ReadAllText(Filename[0]);
     int count = 1;
     while(count < Filename.Length)
        text += System.IO.File.ReadAllText(Filename[count++]);

      // Write the string to a file.
      System.IO.StreamWriter file = new System.IO.StreamWriter(@"F:\\Test\\Test.txt");
      file.Write(text);
      file.Close();

     //Delete the file
      count = 0;
      while (count < Filename.Length)
         File.Delete(Filename[count++]);
}
   
Comments
naraayanan 5-Mar-12 22:22pm
   
Thanks for your reply.I need to append a file information into First File.But you create a New File Name.
Chandrakantt 6-Mar-12 0:17am
   
You can check my other answer which does not creates a new file. It appends to the first file itself.
Code which appends data to the first file itself. As my previous answer creates a new file but this solution appends to the first file itself.
static void Main(string[] args)
{
    string[] Filename = new string[4] {@"F:\Test\2012_03_05_055030.txt", @"F:\Test\2012_03_05_055035.txt",
                        @"F:\Test\2012_03_05_055040.txt", @"F:\Test\2012_03_05_055045.txt"};

    string text="";
    int count = 1;
    while(count < Filename.Length)
        text += System.IO.File.ReadAllText(Filename[count++]);

    // Write the string to a file.
    System.IO.StreamWriter file = new System.IO.StreamWriter(Filename[0]);
    file.Write(text);
    file.Close();

    //Delete the file
    count = 1;
    while (count < Filename.Length)
        File.Delete(Filename[count++]);
}
   
Comments
naraayanan 6-Mar-12 7:30am
   
Thanks friend

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900