XML writer and C # memory stream

I am creating a file using XmlWriter, XmlWriter writer = XmlWriter.Create(fileName); it creates a file, and then I have another function that I call private void EncryptFile(string inputFile, string outputFile) that takes 2 string inputs and outpulfile, and in the end I have two files: encrypted and the other not. I just want one encrypted file, but my encryption function requires an input file that is created by XmlWriter. Is there a way to create a memystream and pass this to my function instead of creating an input file. my encryption function

 private void EncryptFile (string inputFile, string outputFile) string password = @"fdds"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt,RMCrypto.CreateEncryptor(key,key),CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) cs.WriteByte((byte)data); cs.FlushFinalBlock(); fsIn.Close(); cs.Close(); fsCrypt.Close(); } } 
+7
source share
1 answer

You can create an XmlWriter that writes to the memory stream:

 var stream = new MemoryStream(); var writer = XmlWriter.Create(stream); 

Now you can pass this stream to your EncryptFile function instead of inputFile . You must make sure that you do not forget these two things before reading the stream:

  • Make a call to writer.Flush() when you are done writing.
  • Set stream.Position back to 0 before you start reading the stream.
+15
source

All Articles