'Protecting a file by a password [closed]

I have a C# application in which i'd like to create a file :

   string fileName = "test.txt";  // a sample file name
        // Delete the file if it exists.
        if (System.IO.File.Exists(fileName))
        {
            System.IO.File.Delete(fileName);
        }
       // Create the file.
        using (System.IO.FileStream fs = System.IO.File.Create(fileName, 1024))
        {
            // Add some information to the file.
            byte[] info = new System.Text.UTF8Encoding(true).GetBytes("This is some text in the file.");
            fs.Write(info, 0, info.Length);
        }


        string s = "";
        using (System.IO.StreamReader sr = System.IO.File.OpenText(fileName))
        {

            while ((s = sr.ReadLine()) != null)
            {
                textBox1.Text += s;
            }
        }

i need to protect the file by a password outside the program and the file is accessible inside the program without password.

How can i change the snippet to do this task?



Solution 1:[1]

You can not protect a text file with a password out of the box. You would need to encapsulate it, with an other application to do so.

The simplest way, would be to use a Zip File.

As taken form this post by Cheeso using DotNetZip:

using (var zip = new ZipFile())
{
    zip.Password= "VerySecret!!";
    zip.AddFile("test.txt");
    zip.Save("Archive.zip"); 
}

This results in 2 steps.

  1. Create your files
  2. Zip them and choose a password.

Solution 2:[2]

You can also encrypt the files if you dont want to create zip files that have compress/uncompress.

Simple Encryption/Decryption method for encrypting an image file

http://support.microsoft.com/kb/307010

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community