适当的C#流对象

时间:2014-12-24 08:48:43

标签: c# stream

我可以使用StreamWriter写入哪个Stream对象,然后将内容作为字符串获取?

StreamWriter sw= new StreamWriter(streamObject);
string s = streamObject.getString (); // or something like that

编辑: 这里是完整的代码,而不是写入文件,我想写入内存中的流对象,然后将内容作为字符串获取:

  static void DecryptFile(string sInputFilename,
      string sOutputFilename,
      string sKey) {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            //A 64 bit key and IV is required for this provider.
            //Set secret key For DES algorithm.
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            //Set initialization vector.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            //Create a file stream to read the encrypted file back.
            FileStream fsread = new FileStream(sInputFilename,
               FileMode.Open,
               FileAccess.Read);
            //Create a DES decryptor from the DES instance.
            ICryptoTransform desdecrypt = DES.CreateDecryptor();
            //Create crypto stream set to read and do a 
            //DES decryption transform on incoming bytes.
            CryptoStream cryptostreamDecr = new CryptoStream(fsread,
               desdecrypt,
               CryptoStreamMode.Read);
            //Print the contents of the decrypted file.
            StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
            fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
            fsDecrypted.Flush();
            fsDecrypted.Close();
        } 

2 个答案:

答案 0 :(得分:2)

    MemoryStream ms = new MemoryStream();

    using (var writer = new StreamWriter(ms))
    {
        writer.WriteLine("testing a string");
    }

    byte[] contentBytes = ms.ToArray();
    string content = System.Text.Encoding.UTF8.GetString(contentBytes);

答案 1 :(得分:0)

根据您的修改,而不是:

//Print the contents of the decrypted file.
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();

你可以这样写:

static string DecryptFile(string sInputFilename, string sKey)
{
    using (var DES = new DESCryptoServiceProvider())
    {
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

        using (var fsread = new FileStream(sInputFilename, FileMode.Open,FileAccess.Read))
        using (var desdecrypt = DES.CreateDecryptor())
        using (var cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read))
        using (var reader = new StreamReader(cryptostreamDecr))
        {
            // this is a stream content as a string, you don't need to write and read it again
            return reader.ReadToEnd();
        }
    }
}

另请注意,您的代码错过了using实现的IDisposable