我可以使用 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();
}
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);
根据您的编辑,而不是这个:
//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();
}
}
}
另请注意,您的代码错过了IDisposable
实现的using
。