Tuesday 2 October 2012

How to replace text in file in .Net?

Definition: How to replace text in file?

Method:
1) Add namespace
    using System.IO;

Code:
 protected void btnReplace_Click(object sender, EventArgs e)
    {
        string sfileName = string.Empty;
        sfileName = "F:\\Work\\HTML\\Profile.txt";

        File.WriteAllText(
            sfileName,
            File.ReadAllText(sfileName)
                .Replace("Name", "Abhishek")
                .Replace("Address","Block No.123,LBS Road,Mumbai,Maharastra")
                .Replace("Mobile", "93117481253")
       );

    }


How to unzip file in .Net?

Definition: How to unzip file in .Net?

Method: 


1) Add the Ionic.Zip dll through Add reference

2) Add the NameSpaces (using Ionic.Zip;)

In my previous post I show you how to make zip file. Now I will show you how to unzip that zip folder.

Code:
 protected void btnUnZip_Click(object sender, EventArgs e)
    {
        String TargetDirectory = "f:\\Zip\\myzip.zip";

        using (ZipFile zip1 = ZipFile.Read(TargetDirectory))
        {
            zip1.ExtractAll("f:\\UnZip\\myzip",
            Ionic.Zip.ExtractExistingFileAction.DoNotOverwrite);
        }
        File.Delete(TargetDirectory);  //Delete myzip.zip file. It is optional. If you want to delete
                                                         //then delete else don't delete.
    }


How to do zip in .Net? How to make zip file in .Net?

Definition: Make zip file.

Method:
1) Add the Ionic.Zip dll through Add reference

2) Add the NameSpaces (using Ionic.Zip;). 

Code: 

A) Following method will zip whole folder.

protected void btnZip_Click(object sender, EventArgs e)
    {
        string zipfilename = @"f:\\zip\\myzip.zip";  //zipped file name
        string filename = @"F:\\myfiles";         //folder to be zip

        using (ZipFile zip = new ZipFile())
        {
            zip.AddDirectory(filename);
            zip.Save(zipfilename);
        }
    }

Output:
myzip.zip folder at F: drive.

B) Following method will add selected file and folders from different path and add it to archive folder.
 
 protected void btnZip_Click(object sender, EventArgs e)
    {
        string zipfilename = @"f:\\unzip\\myzip.zip";   //zipped file name

        string filename = @"F:\\myfiles";                //folder to be zip

        using (ZipFile zip = new ZipFile())
        {
            //// add this map file into the "images" directory in the zip archive
            zip.AddFile("F:\\Food\\files\\0.png","images");

            //// add the report into a different directory in the archive
            zip.AddFile("F:\\Recipe", "Files");

            zip.AddDirectory("f:\\ticket", "Ticket");


            zip.Save(zipfilename);
        }
    }



Output:
myzip.zip folder at F: drive.
This zip folder will contain 3 folders i.e. images, Files and Ticket.

You run one by one each code and you can see difference between 2 methods.