XML writer and Memory Stream c#

25,374

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

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

Now you can pass this stream to your EncryptFile function instead of an inputFile. You have to make sure that you don't forget these two things before reading the stream:

  1. Make a call to writer.Flush() when you are done writing.
  2. Set stream.Position back to 0 before you start reading the stream.
Share:
25,374
SoftwareDeveloper
Author by

SoftwareDeveloper

Updated on August 05, 2022

Comments

  • SoftwareDeveloper
    SoftwareDeveloper over 1 year

    I am creating a file using XmlWriter, XmlWriter writer = XmlWriter.Create(fileName); it is creating a file and then i have one more function which i am calling private void EncryptFile(string inputFile, string outputFile) which takes 2 string input and outpulfile and in the end i have two files one is encrypted and one is not. I just want one encrypted file but foor my encrypt function it takes inputfile which is created by XmlWriter. Is there any way i can create memorystream and pass that into my function instead of creating a inputfile. my encrypt 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();
            }
        }      
    
  • granadaCoder
    granadaCoder about 9 years
    writer.Flush() was what I was missing. Thx.