2014-02-28 188 views
0

我有2種方法,如下所示,讀取和寫入我的XML文件。加密XML文件並允許從我的代碼讀取/寫入最簡單的方法是什麼?讀取和寫入XML

讀取XML文件

XmlSerializer SerializerObj = new XmlSerializer(typeof(List<ItemsUnderControlObject>)); 
// Create a new file stream for reading the XML file 
FileStream ReadFileStream = new FileStream(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()) + @"\itemlist.xml", FileMode.Open, FileAccess.Read, FileShare.Read); 

// Load the object saved above by using the Deserialize function 
MyGlobals.ListOfItemsToControl = (List<ItemsUnderControlObject>)SerializerObj.Deserialize(ReadFileStream); 
// Cleanup 
ReadFileStream.Close(); 

寫XML文件

// Create a new XmlSerializer instance with the type of the test class 
XmlSerializer SerializerObj = new XmlSerializer(typeof(List<ItemsUnderControlObject>)); 
// Create a new file stream to write the serialized object to a file 
TextWriter WriteFileStream = new StreamWriter(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()) + @"\itemlist.xml"); 
SerializerObj.Serialize(WriteFileStream, MyGlobals.ListOfItemsToControl); 
WriteFileStream.Close(); 
+0

看看這個http://srinivasganaparthi.blogspot.com/2011/04/encrypt-and-decrypt-xml-file-in-c.html –

回答

1

查找到System.Security.Cryptography命名空間提供了一堆,讓您加密/解密類。許多人會用流來解密/解密,所以只需將你的WriteFileStream/ReadFileStream實例傳遞給一個加密類,然後就可以完成了。

以下示例部分基於example in MSDN關於設置AES加密提供程序(並且可以適用於其他加密算法)。它需要一些初始化代碼,這取決於你的實現 - see example那裏。

 using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) 
     { 
      aesAlg.Key = Key; 
      aesAlg.IV = IV; 

      // Create a decrytor to perform the stream transform. 
      ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); 

      // Create the streams used for encryption. 
      using (Stream msEncrypt = new FileStream(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()) + @"\itemlist.xml")) 
      { 
       using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) 
       { 
        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 
        { 
         // Create a new XmlSerializer instance with the type of the test class 
         XmlSerializer SerializerObj = new XmlSerializer(typeof(List<ItemsUnderControlObject>)); 
         // Create a new file stream to write the serialized object to a file 
         SerializerObj.Serialize(swEncrypt, MyGlobals.ListOfItemsToControl); 
        } 
       } 
      } 
     } 
  • 代碼是盡力而爲 - 別有意味的時刻來構建它。所以可能需要一點TLC ...但應該給出一個相當不錯的主意。
+0

我要加密MyGlobals.ListOfItemsToControl - 這是可能嗎? – user1438082

+1

是的。使用上述命名空間中的一個類創建加密流,並將WriteFileStream傳遞給它。 – LB2

+0

您能否根據我上面的代碼給出一個如何做到這一點的代碼示例? – user1438082