XML 编写器和内存流 c#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12848201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:40:29  来源:igfitidea点击:

XML writer and Memory Stream c#

c#memorystreamxmlwriter

提问by SoftwareDeveloper

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

我正在使用 XmlWriter 创建一个文件,XmlWriter writer = XmlWriter.Create(fileName);它正在创建一个文件,然后我有一个我正在调用的函数, private void EncryptFile(string inputFile, string outputFile)它需要 2 个字符串输入和 outpulfile,最后我有两个文件,一个是加密的,一个不是。我只想要一个加密文件,但为了我的加密功能,它需要由 XmlWriter 创建的输入文件。有什么方法可以创建内存流并将其传递给我的函数而不是创建输入文件。我的加密功能

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

采纳答案by Elian Ebbing

You can create an XmlWriterthat writes to a memory stream:

您可以创建一个XmlWriter写入内存流的:

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

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

现在您可以将此流传递给您的EncryptFile函数而不是inputFile. 在阅读流之前,您必须确保不要忘记这两件事:

  1. Make a call to writer.Flush()when you are done writing.
  2. Set stream.Positionback to 0before you start reading the stream.
  1. writer.Flush()写完就打个电话。
  2. 在开始阅读流之前设置stream.Position0