EndOfStreamException Класс

Определение

Исключение, которое выдается при попытке чтения за концом потока.

public ref class EndOfStreamException : System::IO::IOException
public class EndOfStreamException : System.IO.IOException
[System.Serializable]
public class EndOfStreamException : System.IO.IOException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class EndOfStreamException : System.IO.IOException
type EndOfStreamException = class
    inherit IOException
[<System.Serializable>]
type EndOfStreamException = class
    inherit IOException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type EndOfStreamException = class
    inherit IOException
Public Class EndOfStreamException
Inherits IOException
Наследование
EndOfStreamException
Наследование
Атрибуты

Примеры

В следующем примере кода показано, как считывать и записывать Double данные в память с помощью BinaryReader классов и BinaryWriter поверх MemoryStream класса .

using namespace System;
using namespace System::IO;
int main()
{
   int i;
   const int arrayLength = 1000;
   
   // Create random data to write to the stream.
   array<double>^dataArray = gcnew array<double>(arrayLength);
   Random^ randomGenerator = gcnew Random;
   for ( i = 0; i < arrayLength; i++ )
   {
      dataArray[ i ] = 100.1 * randomGenerator->NextDouble();

   }
   BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew MemoryStream );
   try
   {
      
      // Write data to the stream.
      Console::WriteLine( "Writing data to the stream." );
      i = 0;
      for ( i = 0; i < arrayLength; i++ )
      {
         binWriter->Write( dataArray[ i ] );

      }
      
      // Create a reader using the stream from the writer.
      BinaryReader^ binReader = gcnew BinaryReader( binWriter->BaseStream );
      
      // Return to the beginning of the stream.
      binReader->BaseStream->Position = 0;
      try
      {
         
         // Read and verify the data.
         i = 0;
         Console::WriteLine( "Verifying the written data." );
         for ( i = 0; i < arrayLength; i++ )
         {
            if ( binReader->ReadDouble() != dataArray[ i ] )
            {
               Console::WriteLine( "Error writing data." );
               break;
            }

         }
         Console::WriteLine( "The data was written and verified." );
      }
      catch ( EndOfStreamException^ e ) 
      {
         Console::WriteLine( "Error writing data: {0}.", e->GetType()->Name );
      }

   }
   finally
   {
      binWriter->Close();
   }

}
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i;
        const int arrayLength = 1000;

        // Create random data to write to the stream.
        Random randomGenerator = new Random();
        double[] dataArray = new double[arrayLength];
        for(i = 0; i < arrayLength; i++)
        {
            dataArray[i] = 100.1 * randomGenerator.NextDouble();
        }

        using(BinaryWriter binWriter =
            new BinaryWriter(new MemoryStream()))
        {
            // Write the data to the stream.
            Console.WriteLine("Writing data to the stream.");
            for(i = 0; i < arrayLength; i++)
            {
                binWriter.Write(dataArray[i]);
            }

            // Create a reader using the stream from the writer.
            using(BinaryReader binReader =
                new BinaryReader(binWriter.BaseStream))
            {
                try
                {
                    // Return to the beginning of the stream.
                    binReader.BaseStream.Position = 0;

                    // Read and verify the data.
                    Console.WriteLine("Verifying the written data.");
                    for(i = 0; i < arrayLength; i++)
                    {
                        if(binReader.ReadDouble() != dataArray[i])
                        {
                            Console.WriteLine("Error writing data.");
                            break;
                        }
                    }
                    Console.WriteLine("The data was written " +
                        "and verified.");
                }
                catch(EndOfStreamException e)
                {
                    Console.WriteLine("Error writing data: {0}.",
                        e.GetType().Name);
                }
            }
        }
    }
}
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim i As Integer
        Const upperBound As Integer = 1000

        ' Create random data to write to the stream.
        Dim dataArray(upperBound) As Double
        Dim randomGenerator As New Random()
        For i = 0 To upperBound
            dataArray(i) = 100.1 * randomGenerator.NextDouble()
        Next i

        Dim binWriter As New BinaryWriter(New MemoryStream())
        Try

            ' Write data to the stream.
            Console.WriteLine("Writing data to the stream.")
            
            For i = 0 To upperBound
                binWriter.Write(dataArray(i))
            Next i

            ' Create a reader using the stream from the writer.
            Dim binReader As New BinaryReader(binWriter.BaseStream)

            ' Return to the beginning of the stream.
            binReader.BaseStream.Position = 0

            ' Read and verify the data.
            Try
                Console.WriteLine("Verifying the written data.")
                For i = 0 To upperBound
                    If binReader.ReadDouble() <> dataArray(i) Then
                        Console.WriteLine("Error writing data.")
                        Exit For
                    End If
                Next i
                Console.WriteLine("The data was written and verified.")
            Catch ex As EndOfStreamException
                Console.WriteLine("Error writing data: {0}.", _
                    ex.GetType().Name)
            End Try
        Finally
            binWriter.Close()
        End Try

    End Sub
End Class

Комментарии

EndOfStreamException использует COR_E_ENDOFSTREAM HRESULT со значением 0x80070026.

Конструкторы

EndOfStreamException()

Выполняет инициализацию нового экземпляра класса EndOfStreamException со строкой сообщения, которая соответствует строке системного сообщения, и значением HRESULT равным COR_E_ENDOFSTREAM.

EndOfStreamException(SerializationInfo, StreamingContext)

Инициализирует новый экземпляр класса EndOfStreamException с указанными данными о сериализации и контексте.

EndOfStreamException(String)

Выполняет инициализацию нового экземпляра класса EndOfStreamException со строкой сообщения, которая соответствует строке message, и значением HRESULT равным COR_E_ENDOFSTREAM.

EndOfStreamException(String, Exception)

Инициализирует новый экземпляр класса EndOfStreamException указанным сообщением об ошибке и ссылкой на внутреннее исключение, вызвавшее данное исключение.

Свойства

Data

Возвращает коллекцию пар «ключ-значение», предоставляющую дополнительные сведения об исключении.

(Унаследовано от Exception)
HelpLink

Получает или задает ссылку на файл справки, связанный с этим исключением.

(Унаследовано от Exception)
HResult

Возвращает или задает HRESULT — кодированное числовое значение, присвоенное определенному исключению.

(Унаследовано от Exception)
InnerException

Возвращает экземпляр класса Exception, который вызвал текущее исключение.

(Унаследовано от Exception)
Message

Возвращает сообщение, описывающее текущее исключение.

(Унаследовано от Exception)
Source

Возвращает или задает имя приложения или объекта, вызывавшего ошибку.

(Унаследовано от Exception)
StackTrace

Получает строковое представление непосредственных кадров в стеке вызова.

(Унаследовано от Exception)
TargetSite

Возвращает метод, создавший текущее исключение.

(Унаследовано от Exception)

Методы

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetBaseException()

При переопределении в производном классе возвращает исключение Exception, которое является первопричиной одного или нескольких последующих исключений.

(Унаследовано от Exception)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetObjectData(SerializationInfo, StreamingContext)

При переопределении в производном классе задает объект SerializationInfo со сведениями об исключении.

(Унаследовано от Exception)
GetType()

Возвращает тип среды выполнения текущего экземпляра.

(Унаследовано от Exception)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Создает и возвращает строковое представление текущего исключения.

(Унаследовано от Exception)

События

SerializeObjectState
Устаревшие..

Возникает, когда исключение сериализовано для создания объекта состояния исключения, содержащего сериализованные данные об исключении.

(Унаследовано от Exception)

Применяется к

См. также раздел