class StreamReaderWriterDemo : AbastractDemo
{
public override void Run()
{
string message = "hello this is a test 0000";
string result = string.Empty;
try
{
using (var memoryStream = new MemoryStream())
{
StreamWriter streamWriter = new StreamWriter(memoryStream, Encoding.Default);
this.WriteToStream(streamWriter, memoryStream, message);
memoryStream.Position = 0;
StreamReader streamReader = new StreamReader(memoryStream, Encoding.Default);
result = this.ReadFromStream(streamReader, memoryStream);
streamWriter.Dispose();
streamReader.Dispose();
}
}
catch (Exception ex)
{
}
Console.WriteLine(result);
}
private void WriteToStream(StreamWriter streamWriter, MemoryStream stream, string message)
{
streamWriter.Write(message);
streamWriter.Flush();
streamWriter.Close();
}
private string ReadFromStream(StreamReader streamReader, MemoryStream stream)
{
string result;
result = streamReader.ReadToEnd();
return result;
}
}
我无法处理streamReader阅读器,因为streamWriter.Dsipose()已经处理了memoryStream。
所以我有点困惑,这是否意味着我不必处理StreamReader或streamWriter?
处理使用相同内存流的StreamWriter,StreamReader的正确方法是什么?
请给我一些建议?
答案 0 :(得分:4)
实际上,没有什么可怕的事情会发生,因为MemoryStream
和StreamReader
/ StreamWriter
都没有在他们的Dispose()
方法中做任何事情(这可以用.NET之类的东西来验证)反射器)。但你不应该假设这一点。
为了正确,应该处理实现IDisposable
的任何和所有类型的对象。执行此操作的最佳方法是使用您在示例中使用的using
构造。但你也应该将它用于读者和作者,而不仅仅是内存流:
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream, Encoding.Default))
using (var streamReader = new StreamReader(memoryStream, Encoding.Default))
{
this.WriteToStream(streamWriter, memoryStream, message);
memoryStream.Position = 0;
result = this.ReadFromStream(streamReader, memoryStream);
}
处理所有3个对象没有任何问题,即使其中两个对象“包裹”了第三个对象。 (事实上,你应该这样做。)
如果您希望在处理读取器/写入器后能够继续使用内存流,StreamReader
类has a constructor会带一个标志告诉它在底层流之后打开读者被处置。 StreamWriter
有一个类似的构造函数。
答案 1 :(得分:0)
请试试这个:
class StreamReaderWriterDemo
{
public void Run()
{
string message = "hello this is a test 0000";
string result = string.Empty;
try
{
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream, Encoding.Default))
{
WriteToStream(streamWriter, memoryStream, message);
memoryStream.Position = 0;
var streamReader = new StreamReader(memoryStream, Encoding.Default);
result = this.ReadFromStream(streamReader, memoryStream);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine(result);
}
private void WriteToStream(StreamWriter streamWriter, MemoryStream stream, string message)
{
streamWriter.Write(message);
streamWriter.Flush();
}
private string ReadFromStream(StreamReader streamReader, MemoryStream stream)
{
string result;
result = streamReader.ReadToEnd();
return result;
}
}
正如其他答案所提到的,dispose语句由using结构调用。您还在关闭WriteToStream成员内的编写器之前关闭了流。