IT이야기

MemoryStream-닫힌 스트림에 액세스 할 수 없습니다.

cyworld 2021. 3. 29. 21:16
반응형

MemoryStream-닫힌 스트림에 액세스 할 수 없습니다.


안녕하세요 왜 using (var sw = new StreamWriter(ms))돌아옵니다 Cannot access a closed Stream exception. Memory Stream이 코드 위에 있습니다.

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms))
    {                 
        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());                        
        }
    } //error here
}

그것을 고치는 가장 좋은 방법은 무엇입니까? 감사


이는 StreamReader폐기 될 때 기본 스트림을 자동으로 닫기 때문 입니다. using문은 자동으로이 작업을 수행합니다.

그러나 StreamWriter사용중인는 여전히 스트림에서 작업을 시도하고 있습니다 (또한 using작성자에 대한 명령문은 이제를 처리 StreamWriter하려고 시도한 다음 스트림을 닫으려고합니다).

이이다를 해결하는 가장 좋은 방법은 : 사용하지 않는 using및 폐기하지 않습니다 StreamReaderStreamWriter. 이 질문을 참조하십시오 .

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);
    var sr = new StreamReader(ms);

    sw.WriteLine("data");
    sw.WriteLine("data 2");
    ms.Position = 0;

    Console.WriteLine(sr.ReadToEnd());                        
}

당신에 대해 나쁜 느낄 경우 swsr(권장) 코드에서 처리되지 않고 가비지 수집, 당신은 그런 일을 할 수있는 :

StreamWriter sw = null;
StreamReader sr = null;

try
{
    using (var ms = new MemoryStream())
    {
        sw = new StreamWriter(ms);
        sr = new StreamReader(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;

        Console.WriteLine(sr.ReadToEnd());                        
    }
}
finally
{
    if (sw != null) sw.Dispose();
    if (sr != null) sr.Dispose();
}

.net45부터 LeaveOpen생성자 인수를 StreamWriter사용할 수 있으며 using문을 사용할 수 있습니다 .

using (var ms = new MemoryStream())
{
    using (var sw = new StreamWriter(ms, Encoding.UTF8, 1024, true))
    {
        sw.WriteLine("data");
        sw.WriteLine("data 2");    
    }

    ms.Position = 0;
    using (var sr = new StreamReader(ms))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}

StreamReader에 대한 using ()이 종료되면 StreamWriter가 여전히 사용하려고하는 개체를 삭제하고 스트림을 닫습니다.


using 문에서 나올 때 Dispose메서드가 자동으로 호출되어 스트림을 닫습니다.

아래를 시도하십시오.

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());
        }
}    

문제는이 블록입니다.

using (var sr = new StreamReader(ms))
{
    Console.WriteLine(sr.ReadToEnd());                        
}

When the StreamReader is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream is closed. When the StreamWriter gets closed, it tries to flush everything to the MemoryStream, but it is closed.

You should consider not putting the StreamReader in a using block.


In my case (admittedly very arcane and not likely to be reproduced often), this was causing the problem (this code is related to PDF generation using iTextSharp):

PdfPTable tblDuckbilledPlatypi = new PdfPTable(3);
float[] DuckbilledPlatypiRowWidths = new float[] { 42f, 76f };
tblDuckbilledPlatypi.SetWidths(DuckbilledPlatypiRowWidths);

The declaration of a 3-celled/columned table, and then setting only two vals for the width was what caused the problem, apparently. Once I changed "PdfPTable(3)" to "PdfPTable(2)" the problem went the way of the convection oven.

ReferenceURL : https://stackoverflow.com/questions/10934585/memorystream-cannot-access-a-closed-stream

반응형