No Image

Cannot access a closed stream

СОДЕРЖАНИЕ
382 просмотров
10 марта 2020

Привет, почему using (var sw = new StreamWriter(ms)) возвращает Cannot access a closed Stream exception . Memory Stream находится над этим кодом.

Какой лучший способ это исправить? Спасибо

6 ответов

Это потому, что StreamReader автоматически закрывает основной поток при его удалении. Оператор using делает это автоматически.

Однако StreamWriter , который вы используете, все еще пытается работать в потоке (также using оператор для писателя теперь пытается избавиться от StreamWriter , который затем пытается закрыть поток).

Лучший способ исправить это: не использовать using и не избавляться от StreamReader и StreamWriter . Смотрите этот вопрос .

Если вы плохо себя чувствуете по поводу sw и sr будучи собранным мусором без утилизации в вашем коде (как рекомендуется), вы можете сделать что-то вроде этого:

Начиная с .net45 вы можете использовать аргумент конструктора LeaveOpen для StreamWriter и все еще используйте оператор using .

Когда использование () для вашего StreamReader заканчивается, он удаляет объект и закрывает поток, который ваш StreamWriter все еще пытается использовать.

Проблема в этом блоке:

Когда StreamReader закрывается (после выхода из использования), он также закрывает свой основной поток, так что теперь MemoryStream закрыто. Когда StreamWriter закрывается, он пытается сбросить все в MemoryStream , но он закрыт.

Не стоит помещать StreamReader в блок использования.

В моем случае (по общему мнению, очень загадочно и вряд ли будет часто воспроизводиться) это вызывало проблему (этот код связан с генерацией PDF с использованием iTextSharp):

Объявление 3-клеточной /колонной таблицы, а затем установка только двух значений для ширины, по-видимому, и вызвало проблему. После того, как я изменил «PdfPTable (3)» на «PdfPTable (2)», проблема пошла по пути конвекционной печи.

когда он выходит из оператора using, автоматически вызывается метод Dispose , закрывающий поток

Читайте также:  Форматирование разделов жесткого диска windows 10

Hi why using (var sw = new StreamWriter(ms)) returns Cannot access a closed Stream exception . Memory Stream is on top of this code.

What the best way to fix it ? Thanks

6 Answers 6

This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

However, the StreamWriter you’re using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter , which is then trying to close the stream).

The best way to fix this is: don’t use using and don’t dispose of the StreamReader and StreamWriter . See this question.

If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

Posted by: admin December 21, 2017 Leave a comment

Hi why using (var sw = new StreamWriter(ms)) returns Cannot access a closed Stream exception . Memory Stream is on top of this code.

What the best way to fix it ?
Thanks

This is because the StreamReader closes the underlying stream automatically when being disposed of. The using statement does this automatically.

However, the StreamWriter you’re using is still trying to work on the stream (also, the using statement for the writer is now trying to dispose of the StreamWriter , which is then trying to close the stream).

The best way to fix this is: don’t use using and don’t dispose of the StreamReader and StreamWriter . See this question.

If you feel bad about sw and sr being garbage-collected without being disposed of in your code (as recommended), you could do something like that:

Читайте также:  Почему не запускается hitman blood money

When the using() for your StreamReader is ending, it’s disposing the object and closing the stream, which your StreamWriter is still trying to use.

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):

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.

The problem is this block:

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.

when it gets out from the using statement the Dispose method will be called automatically closing the stream

Комментировать
382 просмотров
Комментариев нет, будьте первым кто его оставит

Это интересно
Adblock
detector