2013-09-30 120 views
-2

我有,我想創建一個文件C#應用程序保護文件:通過密碼

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; 
      } 
     } 

我需要通過程序之外的密碼保護的文件和文件訪問內該程序沒有密碼。

如何更改片段來完成此任務?

+3

如果你還沒有嘗試過,甚至自己動手做,請參考System.Security.Cryptography命名空間,並給它一展身手。 – Ashigore

回答

3

您無法用開箱即用密碼保護文本文件。 您需要封裝它,並與其他應用程序一起進行封裝。

最簡單的方法是使用Zip文件。

由於採取這種形式通過post使用CheesoDotNetZip

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

這導致2個步驟。

  1. 創建文件
  2. 壓縮它們並選擇一個密碼。
+0

它給我錯誤ZipFile()類 –