GZipStream.EndRead(IAsyncResult) GZipStream.EndRead(IAsyncResult) GZipStream.EndRead(IAsyncResult) GZipStream.EndRead(IAsyncResult) Method

Определение

Ожидает завершения отложенного асинхронного чтения.Waits for the pending asynchronous read to complete. (Вместо него рекомендуется использовать метод ReadAsync(Byte[], Int32, Int32).)(Consider using the ReadAsync(Byte[], Int32, Int32) method instead.)

public:
 override int EndRead(IAsyncResult ^ async_result);
public override int EndRead (IAsyncResult async_result);
override this.EndRead : IAsyncResult -> int
Public Overrides Function EndRead (async_result As IAsyncResult) As Integer

Параметры

asyncResult
IAsyncResult IAsyncResult IAsyncResult IAsyncResult

Ссылка на отложенный асинхронный запрос, который необходимо завершить.The reference to the pending asynchronous request to finish.

Возвраты

Количество байтов, считанных из потока, от нуля (0) до количества запрошенных байтов.The number of bytes read from the stream, between 0 (zero) and the number of bytes you requested. Объект GZipStream возвращает 0 только в конце потока; в противном случае он блокируется, пока доступен хотя бы один байт.GZipStream returns 0 only at the end of the stream; otherwise, it blocks until at least one byte is available.

Исключения

asyncResult не происходит из метода BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) в текущем потоке.asyncResult did not originate from a BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) method on the current stream.

Операция окончания не может быть выполнена, поскольку поток закрыт.The end operation cannot be performed because the stream is closed.

Примеры

В следующем примере кода показано, как использовать GZipStream класс для сжатия и распаковки файла.The following code example shows how to use the GZipStream class to compress and decompress a file.

using System;
using System.IO;
using System.IO.Compression;

public class Program
{
    private static string directoryPath = @".\temp";
    public static void Main()
    {
        DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
        Compress(directorySelected);

        foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
        {
            Decompress(fileToDecompress);
        }
    }

    public static void Compress(DirectoryInfo directorySelected)
    {
        foreach (FileInfo fileToCompress in directorySelected.GetFiles())
        {
            using (FileStream originalFileStream = fileToCompress.OpenRead())
            {
                if ((File.GetAttributes(fileToCompress.FullName) & 
                   FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                {
                    using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
                    {
                        using (GZipStream compressionStream = new GZipStream(compressedFileStream, 
                           CompressionMode.Compress))
                        {
                            originalFileStream.CopyTo(compressionStream);

                        }
                    }
                    FileInfo info = new FileInfo(directoryPath + Path.DirectorySeparatorChar + fileToCompress.Name + ".gz");
                    Console.WriteLine($"Compressed {fileToCompress.Name} from {fileToCompress.Length.ToString()} to {info.Length.ToString()} bytes.");
                }

            }
        }
    }

    public static void Decompress(FileInfo fileToDecompress)
    {
        using (FileStream originalFileStream = fileToDecompress.OpenRead())
        {
            string currentFileName = fileToDecompress.FullName;
            string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

            using (FileStream decompressedFileStream = File.Create(newFileName))
            {
                using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                {
                    decompressionStream.CopyTo(decompressedFileStream);
                    Console.WriteLine($"Decompressed: {fileToDecompress.Name}");
                }
            }
        }
    }
}
Imports System.IO
Imports System.IO.Compression

Module Module1

    Private directoryPath As String = ".\temp"
    Public Sub Main()
        Dim directorySelected As New DirectoryInfo(directoryPath)
        Compress(directorySelected)

        For Each fileToDecompress As FileInfo In directorySelected.GetFiles("*.gz")
            Decompress(fileToDecompress)
        Next
    End Sub

    Public Sub Compress(directorySelected As DirectoryInfo)
        For Each fileToCompress As FileInfo In directorySelected.GetFiles()
            Using originalFileStream As FileStream = fileToCompress.OpenRead()
                If (File.GetAttributes(fileToCompress.FullName) And FileAttributes.Hidden) <> FileAttributes.Hidden And fileToCompress.Extension <> ".gz" Then
                    Using compressedFileStream As FileStream = File.Create(fileToCompress.FullName & ".gz")
                        Using compressionStream As New GZipStream(compressedFileStream, CompressionMode.Compress)

                            originalFileStream.CopyTo(compressionStream)
                        End Using
                    End Using
                    Dim info As New FileInfo(directoryPath & Path.DirectorySeparatorChar & fileToCompress.Name & ".gz")
                    Console.WriteLine($"Compressed {fileToCompress.Name} from {fileToCompress.Length.ToString()} to {info.Length.ToString()} bytes.")

                End If
            End Using
        Next
    End Sub


    Private Sub Decompress(ByVal fileToDecompress As FileInfo)
        Using originalFileStream As FileStream = fileToDecompress.OpenRead()
            Dim currentFileName As String = fileToDecompress.FullName
            Dim newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length)

            Using decompressedFileStream As FileStream = File.Create(newFileName)
                Using decompressionStream As GZipStream = New GZipStream(originalFileStream, CompressionMode.Decompress)
                    decompressionStream.CopyTo(decompressedFileStream)
                    Console.WriteLine($"Decompressed: {fileToDecompress.Name}")
                End Using
            End Using
        End Using
    End Sub
End Module

Комментарии

Начиная с .NET Framework 4.5.NET Framework 4.5, асинхронные операции чтения можно выполнять с помощью Stream.ReadAsync метод.Starting with the .NET Framework 4.5.NET Framework 4.5, you can perform asynchronous read operations by using the Stream.ReadAsync method. EndRead Метод по-прежнему доступен в .NET Framework 4.5.NET Framework 4.5 для поддержки устаревшего кода; тем не менее, можно реализовать асинхронные операции ввода-вывода проще с помощью новых асинхронных методов.The EndRead method is still available in .NET Framework 4.5.NET Framework 4.5 to support legacy code; however, you can implement asynchronous I/O operations more easily by using the new async methods. Дополнительные сведения см. в разделе Асинхронный файловый ввод-вывод.For more information, see Asynchronous File I/O.

Вызовите этот метод, чтобы определить, сколько байтов, считанных из потока.Call this method to determine how many bytes were read from the stream. Этот метод может вызываться один раз для возврата количество байтов, считанных между вызовами BeginRead и EndRead.This method can be called once to return the amount of bytes read between calls to BeginRead and EndRead.

Этот метод блокируется до завершения операции ввода-вывода.This method blocks until the I/O operation has completed.

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