From 651c690d1ead3caf14c99ac6f666b74fecf49ef9 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 18 Mar 2024 14:09:49 -0700 Subject: [PATCH 01/12] first pass on gzipstream --- xml/System.IO.Compression/GZipStream.xml | 297 +++++++++++------------ 1 file changed, 142 insertions(+), 155 deletions(-) diff --git a/xml/System.IO.Compression/GZipStream.xml b/xml/System.IO.Compression/GZipStream.xml index 085e55fba1b..1ea04cdb300 100644 --- a/xml/System.IO.Compression/GZipStream.xml +++ b/xml/System.IO.Compression/GZipStream.xml @@ -118,22 +118,14 @@ One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing data to the stream. Initializes a new instance of the class by using the specified stream and compression level. - class. - - This constructor overload uses the compression mode . To set the compression mode to another value, use the or overload. +You use this constructor when you want to specify whether compression efficiency or speed is more important for an instance of the class. -## Examples +This constructor overload uses the compression mode . To set the compression mode to another value, use the or overload. - The following example shows how to set the compression mode when creating a object. - - :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs" id="Snippet1"::: - :::code language="fsharp" source="~/snippets/fsharp/System.IO.Compression/GZip/FileCompressionModeExample.fs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: - ]]> @@ -188,36 +180,37 @@ One of the enumeration values that indicates whether to compress data to the stream or decompress data from the stream. Initializes a new instance of the class by using the specified stream and compression mode. - owns the underlying stream, so closing the `stream` parameter also closes the underlying stream. Note that the state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created. - - If an instance of the class is created with the `mode` parameter equal to `Compress` and no further action occurs, the stream will appear as a valid, empty compressed file. - - By default, the compression level is set to when the compression mode is . + owns the underlying stream, so closing the `stream` parameter also closes the underlying stream. Note that the state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created. + +If an instance of the class is created with the `mode` parameter equal to `Compress` and no further action occurs, the stream will appear as a valid, empty compressed file. + +By default, the compression level is set to when the compression mode is . ## Examples The following example shows how to set the compression mode when creating a object. - + :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs" id="Snippet1"::: :::code language="fsharp" source="~/snippets/fsharp/System.IO.Compression/GZip/FileCompressionModeExample.fs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: + ]]> is . - is not a valid enumeration value. - - -or- - - is and is . - - -or- - + is not a valid enumeration value. + + -or- + + is and is . + + -or- + is and is . @@ -264,12 +257,13 @@ The following example shows how to set the compression mode when creating a to leave the stream object open after disposing the object; otherwise, . Initializes a new instance of the class by using the specified stream and compression level, and optionally leaves the stream open. - class, and whether to leave the stream object open after disposing the object. - - This constructor overload uses the compression mode . To set the compression mode to another value, use the or overload. + class, and whether to leave the stream object open after disposing the object. + +This constructor overload uses the compression mode . To set the compression mode to another value, use the or overload. ## Examples @@ -278,7 +272,7 @@ The following example shows how to set the compression level when creating a @@ -330,28 +324,29 @@ The following example shows how to set the compression level when creating a to leave the stream open after disposing the object; otherwise, . Initializes a new instance of the class by using the specified stream and compression mode, and optionally leaves the stream open. - owns the underlying stream, so closing the `stream` parameter also closes the underlying stream. Note that the state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created. - - If an instance of the class is created with the `mode` parameter equal to `Compress` and no further action occurs, the stream will appear as a valid, empty compressed file. - - By default, the compression level is set to when the compression mode is . - + owns the underlying stream, so closing the `stream` parameter also closes the underlying stream. The state of the underlying stream can affect the usability of the stream. Also, no explicit checks are performed, so no additional exceptions are thrown when the new instance is created. + +If an instance of the class is created with the `mode` parameter equal to `Compress` and no further action occurs, the stream will appear as a valid, empty compressed file. + +By default, the compression level is set to when the compression mode is . + ]]> is . - is not a valid value. - - -or- - - is and is . - - -or- - + is not a valid value. + + -or- + + is and is . + + -or- + is and is . @@ -438,9 +433,9 @@ The following example shows how to set the compression level when creating a - - - + + + @@ -449,7 +444,6 @@ The following example shows how to set the compression level when creating a - @@ -458,27 +452,24 @@ The following example shows how to set the compression level when creating a - The byte array to read the data into. The byte array to read the data into. - The byte offset in at which to begin reading data from the stream. + The byte offset at which to begin reading data from the stream. The maximum number of bytes to read. An optional asynchronous callback, to be called when the read operation is complete. - An optional asynchronous callback, to be called when the read operation is complete. A user-provided object that distinguishes this particular asynchronous read request from other requests. - A user-provided object that distinguishes this particular asynchronous read request from other requests. Begins an asynchronous read operation. (Consider using the method instead.) An object that represents the asynchronous read operation, which could still be pending. - - The method tried to read asynchronously past the end of the stream, or a disk error occurred. + The method tried to read asynchronously past the end of the stream, or a disk error occurred. One or more of the arguments is invalid. Methods were called after the stream was closed. The current implementation does not support the read operation. @@ -526,9 +517,9 @@ The following example shows how to set the compression level when creating a - - - + + + @@ -537,7 +528,6 @@ The following example shows how to set the compression level when creating a - @@ -546,35 +536,33 @@ The following example shows how to set the compression level when creating a - The buffer containing data to write to the current stream. The buffer containing data to write to the current stream. - The byte offset in at which to begin writing. + The byte offset at which to begin writing. The maximum number of bytes to write. An optional asynchronous callback to be called when the write operation is complete. - An optional asynchronous callback to be called when the write operation is complete. A user-provided object that distinguishes this particular asynchronous write request from other requests. - A user-provided object that distinguishes this particular asynchronous write request from other requests. Begins an asynchronous write operation. (Consider using the method instead.) An object that represents the asynchronous write operation, which could still be pending. - method. The method is still available in .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](/dotnet/standard/io/asynchronous-file-i-o). - - The method starts an asynchronous write operation to a stream object. - - You must create a callback method that implements the delegate and pass its name to the method. - + method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). + +The method starts an asynchronous write operation to a stream object. + +You must create a callback method that implements the delegate and pass its name to the method. + ]]> - The underlying stream is . - - -or- - + The underlying stream is . + + -or- + The underlying stream is closed. @@ -616,7 +604,7 @@ The following example shows how to set the compression level when creating a Gets a value indicating whether the stream supports reading while decompressing a file. - if the value is and the underlying stream supports reading and is not closed; otherwise, . + if the value is and the underlying stream supports reading and is not closed; otherwise, . To be added. When you inherit from , you must override the following members: , , and . @@ -706,7 +694,7 @@ The following example shows how to set the compression level when creating a Gets a value indicating whether the stream supports writing. - if the value is , and the underlying stream supports writing and is not closed; otherwise, . + if the value is and the underlying stream supports writing and is not closed; otherwise, . To be added. When you inherit from , you must override the following members: , , and . @@ -748,7 +736,7 @@ The following example shows how to set the compression level when creating a The stream to which the contents of the current GZip stream will be copied. The size of the buffer. This value must be greater than zero. The default size is 81920. - Reads the bytes from the current GZip stream and writes them to another stream, using a specified buffer size. + Reads the bytes from the current GZip stream and writes them to another stream, using the specified buffer size. method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. +The method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. If the operation is canceled before it completes, the returned task contains the value for the property. @@ -860,19 +848,20 @@ This method stores in the task it returns all non-usage exceptions that the meth to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. + +When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -914,7 +903,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ## Remarks -The `DisposeAsync` method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. +The `DisposeAsync` method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. This method disposes the GZip stream by writing any changes to the backing store and closing the stream to release resources. @@ -959,22 +948,21 @@ Calling `DisposeAsync` allows the resources used by the - The reference to the pending asynchronous request to finish. - The reference to the pending asynchronous request to finish. Waits for the pending asynchronous read to complete. (Consider using the method instead.) The number of bytes read from the stream, between 0 (zero) and the number of bytes you requested. returns 0 only at the end of the stream; otherwise, it blocks until at least one byte is available. - method. The method is still available in .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](/dotnet/standard/io/asynchronous-file-i-o). - - Call this method to determine how many bytes were read from the stream. This method can be called once to return the amount of bytes read between calls to and . - - This method blocks until the I/O operation has completed. + method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). + +Call this method to determine how many bytes were read from the stream. This method can be called once to return the amount of bytes read between calls to and . + +This method blocks until the I/O operation has completed. ]]> @@ -1020,26 +1008,25 @@ Calling `DisposeAsync` allows the resources used by the - The object that represents the asynchronous call. - The object that represents the asynchronous call. Handles the end of an asynchronous write operation. (Consider using the method instead.) - method. The method is still available in .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](/dotnet/standard/io/asynchronous-file-i-o). - - The method completes the asynchronous write operation started in the method. - + method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). + +The method completes the asynchronous write operation started in the method. + ]]> - The underlying stream is . - - -or- - + The underlying stream is . + + -or- + The underlying stream is closed. @@ -1274,7 +1261,7 @@ This method stores in the task it returns all non-usage exceptions that the meth Use the property to determine whether the current instance supports reading. Use the method to read asynchronously from the current stream. -This method read a maximum of `buffer.Length` bytes from the current stream and store them in `buffer`. The current position within the GZip stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the GZip stream remains unchanged. This method will block until at least one byte of data can be read, in the event that no data is available. `Read` returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). The method is free to return fewer bytes than requested even if the end of the stream has not been reached. +This method reads a maximum of `buffer.Length` bytes from the current stream and stores them in `buffer`. The current position within the GZip stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the GZip stream remains unchanged. In the event that no data is available, this method blocks until at least one byte of data can be read. `Read` returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). The method is free to return fewer bytes than requested even if the end of the stream has not been reached. Use for reading primitive data types. @@ -1330,17 +1317,17 @@ This method read a maximum of `buffer.Length` bytes from the current stream and The array used to store decompressed bytes. - To be added. - The byte offset in at which the read bytes will be placed. + The array used to store decompressed bytes. + The byte offset at which the read bytes will be placed. The maximum number of decompressed bytes to read. Reads a number of decompressed bytes into the specified byte array. The number of bytes that were decompressed into the byte array. If the end of the stream has been reached, zero or the number of bytes read is returned. - is thrown as one of the last operations. A cyclic redundancy check (CRC) is performed as one of the last operations of this method. +If data is found in an invalid format, an is thrown. A cyclic redundancy check (CRC) is performed as one of the last operations of this method. ## Examples @@ -1349,22 +1336,22 @@ The following example shows how to compress and decompress bytes by using the - is . - The value was when the object was created. - + or is . + The value was when the object was created. + -or- - + The underlying stream does not support reading. - or is less than zero. - - -or- - - length minus the index starting point is less than . + or is less than zero. + + -or- + + or length minus the index starting point is less than . The data is in an invalid format. The stream is closed. @@ -1416,7 +1403,7 @@ The following example shows how to compress and decompress bytes by using the property to determine whether the current instance supports reading. @@ -1471,18 +1458,18 @@ If the operation is canceled before it completes, the returned task contains the The buffer to write the data into. - To be added. - The byte offset in at which to begin writing data from the GZip stream. + The buffer to write the data into. + The byte offset at which to begin writing data from the GZip stream. The maximum number of bytes to read. The token to monitor for cancellation requests. The default value is . Asynchronously reads a sequence of bytes from the current GZip stream into a byte array, advances the position within the GZip stream by the number of bytes read, and monitors cancellation requests. - A task that represents the asynchronous read operation, which wraps the total number of bytes read into the . The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the GZip stream has been reached. + A task that represents the asynchronous read operation, which wraps the total number of bytes read. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the GZip stream has been reached. property to determine whether the current instance supports reading. @@ -1732,16 +1719,16 @@ If the write operation is successful, the position within the GZip stream advanc The buffer that contains the data to compress. - To be added. - The byte offset in from which the bytes will be read. + The buffer that contains the data to compress. + The byte offset from which the bytes will be read. The maximum number of bytes to write. Writes compressed bytes to the underlying GZip stream from the specified byte array. - or method is called. +The write operation might not occur immediately but is buffered until the buffer size is reached or until the or method is called. ## Examples @@ -1749,7 +1736,7 @@ The following example shows how to compress and decompress bytes by using the @@ -1803,7 +1790,7 @@ The following example shows how to compress and decompress bytes by using the property to determine whether the current instance supports writing. @@ -1858,8 +1845,8 @@ If the operation is canceled before it completes, the returned task contains the The buffer that contains the data to compress. - To be added. - The zero-based byte offset in from which to begin copying bytes to the GZip stream. + The buffer that contains the data to compress. + The zero-based byte offset from which to begin copying bytes to the GZip stream. The maximum number of bytes to write. The token to monitor for cancellation requests. The default value is . Asynchronously writes compressed bytes to the underlying GZip stream from the specified byte array. @@ -1869,7 +1856,7 @@ If the operation is canceled before it completes, the returned task contains the ## Remarks -The `WriteAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. +The `WriteAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. Use the property to determine whether the current instance supports writing. From c4d6802be9f175ea424149c3613779e683e7b508 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 18 Mar 2024 14:50:10 -0700 Subject: [PATCH 02/12] add warning to gzipstream read methods --- ...d_Byte_Int32_Int32_AsyncCallback_Object.md | 11 -------- .../GZip/FileCompressionModeExample.cs | 14 +++++----- .../System.IO.Compression/GZip/GZip.csproj | 5 ++-- .../GZip/MemoryWriteReadExample.cs | 18 ++++++++---- .../System.IO.Compression/GZip/Program.cs | 8 ++++++ xml/System.IO.Compression/GZipStream.xml | 28 +++++++++++++++---- 6 files changed, 53 insertions(+), 31 deletions(-) delete mode 100644 includes/remarks/System.IO.Compression/GZipStream/BeginRead_Byte_Int32_Int32_AsyncCallback_Object.md create mode 100644 snippets/csharp/System.IO.Compression/GZip/Program.cs diff --git a/includes/remarks/System.IO.Compression/GZipStream/BeginRead_Byte_Int32_Int32_AsyncCallback_Object.md b/includes/remarks/System.IO.Compression/GZipStream/BeginRead_Byte_Int32_Int32_AsyncCallback_Object.md deleted file mode 100644 index 38900b5e70b..00000000000 --- a/includes/remarks/System.IO.Compression/GZipStream/BeginRead_Byte_Int32_Int32_AsyncCallback_Object.md +++ /dev/null @@ -1,11 +0,0 @@ -Starting with the .NET Framework 4.5, you can perform asynchronous read operations by using the method. The method is still available in .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](/dotnet/standard/io/asynchronous-file-i-o). - -Pass the return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. You can do this either by using the same code that called or in a callback passed to . - -The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. - -Multiple simultaneous asynchronous requests render the request completion order uncertain. - -Use the property to determine whether the current object supports reading. - -If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from . Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling . diff --git a/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs b/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs index 4cb0ea0834d..9be9db1ba32 100644 --- a/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs +++ b/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs @@ -10,7 +10,7 @@ public class FileCompressionModeExample private const string CompressedFileName = "compressed.gz"; private const string DecompressedFileName = "decompressed.txt"; - public static void Main() + public static void Run() { CreateFileToCompress(); CompressFile(); @@ -21,11 +21,11 @@ public static void Main() /* Output: - The original file 'original.txt' weighs 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + The original file 'original.txt' is 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." - The compressed file 'compressed.gz' weighs 283 bytes. + The compressed file 'compressed.gz' is 283 bytes. - The decompressed file 'decompressed.txt' weighs 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + The decompressed file 'decompressed.txt' is 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." */ } @@ -53,9 +53,9 @@ private static void PrintResults() long compressedSize = new FileInfo(CompressedFileName).Length; long decompressedSize = new FileInfo(DecompressedFileName).Length; - Console.WriteLine($"The original file '{OriginalFileName}' weighs {originalSize} bytes. Contents: \"{File.ReadAllText(OriginalFileName)}\""); - Console.WriteLine($"The compressed file '{CompressedFileName}' weighs {compressedSize} bytes."); - Console.WriteLine($"The decompressed file '{DecompressedFileName}' weighs {decompressedSize} bytes. Contents: \"{File.ReadAllText(DecompressedFileName)}\""); + Console.WriteLine($"The original file '{OriginalFileName}' is {originalSize} bytes. Contents: \"{File.ReadAllText(OriginalFileName)}\""); + Console.WriteLine($"The compressed file '{CompressedFileName}' is {compressedSize} bytes."); + Console.WriteLine($"The decompressed file '{DecompressedFileName}' is {decompressedSize} bytes. Contents: \"{File.ReadAllText(DecompressedFileName)}\""); } private static void DeleteFiles() diff --git a/snippets/csharp/System.IO.Compression/GZip/GZip.csproj b/snippets/csharp/System.IO.Compression/GZip/GZip.csproj index 73920c4ae07..f432dbe7e6f 100644 --- a/snippets/csharp/System.IO.Compression/GZip/GZip.csproj +++ b/snippets/csharp/System.IO.Compression/GZip/GZip.csproj @@ -1,10 +1,9 @@ - + Exe - net6.0 + net8.0 enable - MemoryWriteReadExample diff --git a/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs b/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs index 9c12cab81a7..64c3721429d 100644 --- a/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs +++ b/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs @@ -9,7 +9,7 @@ public static class MemoryWriteReadExample private const string Message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; private static readonly byte[] s_messageBytes = Encoding.ASCII.GetBytes(Message); - public static void Main() + public static void Run() { Console.WriteLine($"The original string length is {s_messageBytes.Length} bytes."); using var stream = new MemoryStream(); @@ -35,10 +35,18 @@ private static int DecompressStreamToBytes(Stream stream) { stream.Position = 0; int bufferSize = 512; - byte[] decompressedBytes = new byte[bufferSize]; - using var decompressor = new GZipStream(stream, CompressionMode.Decompress); - int length = decompressor.Read(decompressedBytes, 0, bufferSize); - return length; + byte[] buffer = new byte[bufferSize]; + using var gzipStream = new GZipStream(stream, CompressionMode.Decompress); + + int totalRead = 0; + while (totalRead < buffer.Length) + { + int bytesRead = gzipStream.Read(buffer, totalRead, buffer.Length - totalRead); + if (bytesRead == 0) break; + totalRead += bytesRead; + } + + return totalRead; } } // diff --git a/snippets/csharp/System.IO.Compression/GZip/Program.cs b/snippets/csharp/System.IO.Compression/GZip/Program.cs new file mode 100644 index 00000000000..d90de56754b --- /dev/null +++ b/snippets/csharp/System.IO.Compression/GZip/Program.cs @@ -0,0 +1,8 @@ +public static class Program +{ + public static void Main() + { + MemoryWriteReadExample.Run(); + //FileCompressionModeExample.Run(); + } +} diff --git a/xml/System.IO.Compression/GZipStream.xml b/xml/System.IO.Compression/GZipStream.xml index 1ea04cdb300..8c250fe5a02 100644 --- a/xml/System.IO.Compression/GZipStream.xml +++ b/xml/System.IO.Compression/GZipStream.xml @@ -465,8 +465,20 @@ By default, the compression level is set to [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). +Starting with .NET Framework 4.5, you can perform asynchronous read operations by using the method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). + +Pass the return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. You can do this either by using the same code that called or in a callback passed to . + +The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. + +Multiple simultaneous asynchronous requests render the request completion order uncertain. + +Use the property to determine whether the current object supports reading. + +If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from . Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling . ]]> The method tried to read asynchronously past the end of the stream, or a disk error occurred. @@ -1257,13 +1269,14 @@ This method stores in the task it returns all non-usage exceptions that the meth [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). Use the property to determine whether the current instance supports reading. Use the method to read asynchronously from the current stream. This method reads a maximum of `buffer.Length` bytes from the current stream and stores them in `buffer`. The current position within the GZip stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the GZip stream remains unchanged. In the event that no data is available, this method blocks until at least one byte of data can be read. `Read` returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). The method is free to return fewer bytes than requested even if the end of the stream has not been reached. - Use for reading primitive data types. +Use for reading primitive data types. ]]> @@ -1327,6 +1340,9 @@ This method reads a maximum of `buffer.Length` bytes from the current stream and ## Remarks +> [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). + If data is found in an invalid format, an is thrown. A cyclic redundancy check (CRC) is performed as one of the last operations of this method. ## Examples @@ -1401,7 +1417,8 @@ The following example shows how to compress and decompress bytes by using the [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). The `ReadAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. @@ -1467,7 +1484,8 @@ If the operation is canceled before it completes, the returned task contains the [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). The `ReadAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. From 2196d15a28589cc3cbd4908e6a2ef4e27da2b107 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 18 Mar 2024 15:06:07 -0700 Subject: [PATCH 03/12] last gzip updates --- .../GZipStream/GZipStream.md | 14 -------------- xml/System.IO.Compression/GZipStream.xml | 15 ++++++++++++++- 2 files changed, 14 insertions(+), 15 deletions(-) delete mode 100644 includes/remarks/System.IO.Compression/GZipStream/GZipStream.md diff --git a/includes/remarks/System.IO.Compression/GZipStream/GZipStream.md b/includes/remarks/System.IO.Compression/GZipStream/GZipStream.md deleted file mode 100644 index 37b3fd82b6f..00000000000 --- a/includes/remarks/System.IO.Compression/GZipStream/GZipStream.md +++ /dev/null @@ -1,14 +0,0 @@ -This class represents the gzip data format, which uses an industry-standard algorithm for lossless file compression and decompression. The format includes a cyclic redundancy check value for detecting data corruption. The gzip data format uses the same algorithm as the class, but can be extended to use other compression formats. The format can be readily implemented in a manner not covered by patents. - -Starting with the .NET Framework 4.5, the class uses the zlib library for compression. As a result, it provides a better compression algorithm and, in most cases, a smaller compressed file than it provides in earlier versions of the .NET Framework. - -Compressed objects written to a file with an extension of .gz can be decompressed using many common compression tools; however, this class does not inherently provide functionality for adding files to or extracting files from zip archives. - -The compression functionality in and is exposed as a stream. Data is read on a byte-by-byte basis, so it is not possible to perform multiple passes to determine the best method for compressing entire files or large blocks of data. The and classes are best used on uncompressed sources of data. If the source data is already compressed, using these classes may actually increase the size of the stream. - -## Examples - -The following example shows how to use the class to compress and decompress a directory of files. - -:::code language="csharp" source="~/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: diff --git a/xml/System.IO.Compression/GZipStream.xml b/xml/System.IO.Compression/GZipStream.xml index 8c250fe5a02..75ec2d5c1ec 100644 --- a/xml/System.IO.Compression/GZipStream.xml +++ b/xml/System.IO.Compression/GZipStream.xml @@ -58,7 +58,20 @@ class, but can be extended to use other compression formats. The format can be readily implemented in a manner not covered by patents. + +Starting with .NET Framework 4.5, the class uses the zlib library for compression. As a result, it provides a better compression algorithm and, in most cases, a smaller compressed file than it provides in earlier versions of .NET Framework. + +Compressed objects written to a file with an extension of .gz can be decompressed using many common compression tools; however, this class does not inherently provide functionality for adding files to or extracting files from zip archives. + +The compression functionality in and is exposed as a stream. Data is read on a byte-by-byte basis, so it's not possible to perform multiple passes to determine the best method for compressing entire files or large blocks of data. The and classes are best used on uncompressed sources of data. If the source data is already compressed, using these classes may actually increase the size of the stream. + +## Examples + +The following example shows how to use the class to compress and decompress a directory of files. + +:::code language="csharp" source="~/snippets/csharp/System.IO.Compression/GZip/FileCompressionModeExample.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/GZip/FileCompressionModeExample.vb" id="Snippet1"::: ]]> From 0143969983ee7d0b6cabbc8596cf6be0df765d87 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 18 Mar 2024 15:34:04 -0700 Subject: [PATCH 04/12] initial cleanup for DeflateStream --- .../.ctor_Stream_CompressionMode.md | 1 - ...d_Byte_Int32_Int32_AsyncCallback_Object.md | 12 - ...e_Byte_Int32_Int32_AsyncCallback_Object.md | 11 - .../DeflateStream/DeflateStream.md | 14 - xml/System.IO.Compression/DeflateStream.xml | 281 +++++++++--------- 5 files changed, 141 insertions(+), 178 deletions(-) delete mode 100644 includes/remarks/System.IO.Compression/DeflateStream/BeginRead_Byte_Int32_Int32_AsyncCallback_Object.md delete mode 100644 includes/remarks/System.IO.Compression/DeflateStream/BeginWrite_Byte_Int32_Int32_AsyncCallback_Object.md delete mode 100644 includes/remarks/System.IO.Compression/DeflateStream/DeflateStream.md diff --git a/includes/remarks/System.IO.Compression/DeflateStream/.ctor_Stream_CompressionMode.md b/includes/remarks/System.IO.Compression/DeflateStream/.ctor_Stream_CompressionMode.md index c8c7f930ffd..6144d6c5bda 100644 --- a/includes/remarks/System.IO.Compression/DeflateStream/.ctor_Stream_CompressionMode.md +++ b/includes/remarks/System.IO.Compression/DeflateStream/.ctor_Stream_CompressionMode.md @@ -12,4 +12,3 @@ The following example shows how to use the method. The method is still available in the .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](/dotnet/standard/io/asynchronous-file-i-o). - -Pass the return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. You can do this either by using the same code that called or in a callback passed to . - -The current position in the stream is updated when the asynchronous read or write operation is issued, not when the I/O operation completes. - -Multiple simultaneous asynchronous requests render the request completion order uncertain. - -Use the property to determine whether the current object supports reading. - -If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from . Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling . - \ No newline at end of file diff --git a/includes/remarks/System.IO.Compression/DeflateStream/BeginWrite_Byte_Int32_Int32_AsyncCallback_Object.md b/includes/remarks/System.IO.Compression/DeflateStream/BeginWrite_Byte_Int32_Int32_AsyncCallback_Object.md deleted file mode 100644 index 677f67286ea..00000000000 --- a/includes/remarks/System.IO.Compression/DeflateStream/BeginWrite_Byte_Int32_Int32_AsyncCallback_Object.md +++ /dev/null @@ -1,11 +0,0 @@ -Starting with the .NET Framework 4.5, you can perform asynchronous write operations by using the method. The method is still available in the .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](/dotnet/standard/io/asynchronous-file-i-o). - -Pass the object returned by the current method to to ensure that the write completes and frees resources appropriately. You can do this either by using the same code that called or in a callback passed to . If an error occurs during an asynchronous write operation, an exception will not be thrown until is called with the returned by this method. - -If a stream is writable, writing at the end of the stream expands the stream. - -The current position in the stream is updated when you issue the asynchronous read or write operation, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. - -Use the property to determine whether the current object supports writing. - -If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from . Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling . diff --git a/includes/remarks/System.IO.Compression/DeflateStream/DeflateStream.md b/includes/remarks/System.IO.Compression/DeflateStream/DeflateStream.md deleted file mode 100644 index 311d0325d69..00000000000 --- a/includes/remarks/System.IO.Compression/DeflateStream/DeflateStream.md +++ /dev/null @@ -1,14 +0,0 @@ -This class represents the Deflate algorithm, which is an industry-standard algorithm for lossless file compression and decompression. Starting with the .NET Framework 4.5, the class uses the zlib library. As a result, it provides a better compression algorithm and, in most cases, a smaller compressed file than it provides in earlier versions of the .NET Framework. - -This class does not inherently provide functionality for adding files to or extracting files from zip archives. To work with zip archives, use the and the classes. - -The class uses the same compression algorithm as the gzip data format used by the class. - -The compression functionality in and is exposed as a stream. Data is read on a byte-by-byte basis, so it is not possible to perform multiple passes to determine the best method for compressing entire files or large blocks of data. The and classes are best used on uncompressed sources of data. If the source data is already compressed, using these classes may actually increase the size of the stream. - -## Examples - -The following example shows how to use the class to compress and decompress a file. - -:::code language="csharp" source="~/snippets/csharp/System.IO.Compression/Deflate/FileCompressionModeExample.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/FileCompressionModeExample.vb" id="Snippet1"::: diff --git a/xml/System.IO.Compression/DeflateStream.xml b/xml/System.IO.Compression/DeflateStream.xml index 873b2e18696..08625d3b67f 100644 --- a/xml/System.IO.Compression/DeflateStream.xml +++ b/xml/System.IO.Compression/DeflateStream.xml @@ -58,7 +58,20 @@ class uses the zlib library. As a result, it provides a better compression algorithm and, in most cases, a smaller compressed file than it provides in earlier versions of .NET Framework. + +This class does not inherently provide functionality for adding files to or extracting files from zip archives. To work with zip archives, use the and the classes. + +The class uses the same compression algorithm as the gzip data format used by the class. + +The compression functionality in and is exposed as a stream. Data is read on a byte-by-byte basis, so it is not possible to perform multiple passes to determine the best method for compressing entire files or large blocks of data. The and classes are best used on uncompressed sources of data. If the source data is already compressed, using these classes may actually increase the size of the stream. + +## Examples + +The following example shows how to use the class to compress and decompress a file. + +:::code language="csharp" source="~/snippets/csharp/System.IO.Compression/Deflate/FileCompressionModeExample.cs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/FileCompressionModeExample.vb" id="Snippet1"::: ]]> @@ -73,12 +86,10 @@ Initializes a new instance of the class. - class to compress a file larger than 4 GB will cause an exception. - Using the class to compress a file larger than 4 GB will cause an exception. - ]]> @@ -127,7 +138,7 @@ ## Remarks - You use this constructor when you want to specify whether compression efficiency or speed is more important for an instance of the class. +You use this constructor when you want to specify whether compression efficiency or speed is more important for an instance of the class. [!INCLUDE[remarks](~/includes/remarks/System.IO.Compression/DeflateStream/.ctor_Stream_CompressionLevel.md)] @@ -194,14 +205,14 @@ is . - is not a valid value. - - -or- - - is and is . - - -or- - + is not a valid value. + + -or- + + is and is . + + -or- + is and is . @@ -316,14 +327,14 @@ You use this constructor when you want to specify whether compression efficiency is . - is not a valid value. - - -or- - - is and is . - - -or- - + is not a valid value. + + -or- + + is and is . + + -or- + is and is . @@ -415,10 +426,10 @@ You use this constructor when you want to specify whether compression efficiency System.IAsyncResult - + - - + + @@ -427,7 +438,6 @@ You use this constructor when you want to specify whether compression efficiency - @@ -436,23 +446,29 @@ You use this constructor when you want to specify whether compression efficiency - - The byte array to read the data into. The byte array to read the data into. - The byte offset in at which to begin reading data from the stream. + The byte offset at which to begin reading data from the stream. The maximum number of bytes to read. An optional asynchronous callback, to be called when the read operation is complete. - An optional asynchronous callback, to be called when the read operation is complete. A user-provided object that distinguishes this particular asynchronous read request from other requests. - A user-provided object that distinguishes this particular asynchronous read request from other requests. Begins an asynchronous read operation. (Consider using the method instead.) An object that represents the asynchronous read operation, which could still be pending. - method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). -[!INCLUDE[remarks](~/includes/remarks/System.IO.Compression/DeflateStream/BeginRead_Byte_Int32_Int32_AsyncCallback_Object.md)] +Pass the return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. You can do this either by using the same code that called or in a callback passed to . + +The current position in the stream is updated when the asynchronous read or write operation is issued, not when the I/O operation completes. + +Multiple simultaneous asynchronous requests render the request completion order uncertain. + +Use the property to determine whether the current object supports reading. + +If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from . Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling . ]]> @@ -504,9 +520,9 @@ You use this constructor when you want to specify whether compression efficiency - - - + + + @@ -515,7 +531,6 @@ You use this constructor when you want to specify whether compression efficiency - @@ -524,23 +539,29 @@ You use this constructor when you want to specify whether compression efficiency - - The buffer to write data from. The buffer to write data from. - The byte offset in to begin writing from. + The byte offset to begin writing from. The maximum number of bytes to write. An optional asynchronous callback, to be called when the write operation is complete. - An optional asynchronous callback, to be called when the write operation is complete. A user-provided object that distinguishes this particular asynchronous write request from other requests. - A user-provided object that distinguishes this particular asynchronous write request from other requests. Begins an asynchronous write operation. (Consider using the method instead.) An object that represents the asynchronous write operation, which could still be pending. method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). + +Pass the object returned by the current method to to ensure that the write completes and frees resources appropriately. You can do this either by using the same code that called or in a callback passed to . If an error occurs during an asynchronous write operation, an exception will not be thrown until is called with the returned by this method. + +If a stream is writable, writing at the end of the stream expands the stream. + +The current position in the stream is updated when you issue the asynchronous read or write operation, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. + +Use the property to determine whether the current object supports writing. + +If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from . Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling . ]]> @@ -768,7 +789,7 @@ Copying begins at the current position in the current Deflate stream and does no ## Remarks -The `CopyToAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. +The `CopyToAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. If the operation is canceled before it completes, the returned task contains the value for the property. @@ -824,20 +845,20 @@ This method stores in the task it returns all non-usage exceptions that the meth to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. - + method and the method, if it has been overridden. invokes the protected method with the `disposing` parameter set to `true`. `Finalize` invokes with `disposing` set to `false`. + +When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - + can be called multiple times by other objects. When overriding be careful not to reference objects that have been previously disposed of in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). @@ -879,7 +900,7 @@ This method stores in the task it returns all non-usage exceptions that the meth ## Remarks -The `DisposeAsync` method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. +The `DisposeAsync` method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. This method disposes the Deflate stream by writing any changes to the backing store and closing the stream to release resources. @@ -924,24 +945,22 @@ Calling `DisposeAsync` allows the resources used by the - The reference to the pending asynchronous request to finish. - The reference to the pending asynchronous request to finish. Waits for the pending asynchronous read to complete. (Consider using the method instead.) The number of bytes read from the stream, between 0 (zero) and the number of bytes you requested. returns 0 only at the end of the stream; otherwise, it blocks until at least one byte is available. - method. The method is still available in the .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](/dotnet/standard/io/asynchronous-file-i-o). - - Call this method to determine how many bytes were read from the stream. This method can be called once to return the amount of bytes read between calls to and . - - This method blocks until the I/O operation has completed. - + method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). + +Call this method to determine how many bytes were read from the stream. This method can be called once to return the amount of bytes read between calls to and . + +This method blocks until the I/O operation has completed. + ]]> @@ -991,23 +1010,21 @@ The stream is . - A reference to the outstanding asynchronous I/O request. - A reference to the outstanding asynchronous I/O request. Ends an asynchronous write operation. (Consider using the method instead.) - method. The method is still available in the .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](/dotnet/standard/io/asynchronous-file-i-o). - - must be called only once for every call to the method. - - This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to . Exceptions thrown by the thread pool thread will not be visible when calling . - + method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). + + must be called only once for every call to the method. + +This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to . Exceptions thrown by the thread pool thread will not be visible when calling . + ]]> @@ -1061,12 +1078,10 @@ The end write call is invalid. The current implementation of this method has no functionality. - . - Flushes the internal buffer if the compression mode is set to . - ]]> The stream is closed. @@ -1110,8 +1125,6 @@ The end write call is invalid. value for the property. This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . @@ -1255,7 +1268,7 @@ Use the property to determ This method read a maximum of `buffer.Length` bytes from the current stream and store them in `buffer`. The current position within the Deflate stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the Deflate stream remains unchanged. This method will block until at least one byte of data can be read, in the event that no data is available. `Read` returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). The method is free to return fewer bytes than requested even if the end of the stream has not been reached. - Use for reading primitive data types. +Use for reading primitive data types. ]]> @@ -1309,36 +1322,37 @@ This method read a maximum of `buffer.Length` bytes from the current stream and The array to store decompressed bytes. - To be added. - The byte offset in at which the read bytes will be placed. + The array to store decompressed bytes. + The byte offset at which the read bytes will be placed. The maximum number of decompressed bytes to read. Reads a number of decompressed bytes into the specified byte array. The number of bytes that were read into the byte array. - and methods. - - :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs" id="Snippet1"::: - :::code language="fsharp" source="~/snippets/fsharp/System.IO.Compression/Deflate/MemoryWriteReadExample.fs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/MemoryWriteReadExample.vb" id="Snippet1"::: - + and methods. + +:::code language="csharp" source="~/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs" id="Snippet1"::: +:::code language="fsharp" source="~/snippets/fsharp/System.IO.Compression/Deflate/MemoryWriteReadExample.fs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/MemoryWriteReadExample.vb" id="Snippet1"::: + ]]> - is . - The value was when the object was created. - + or is . + The value was when the object was created. + -or- - + The underlying stream does not support reading. - or is less than zero. - - -or- - - length minus the index starting point is less than . + or is less than zero. + + -or- + + or length minus the index starting point is less than . The data is in an invalid format. The stream is closed. @@ -1388,9 +1402,7 @@ This method read a maximum of `buffer.Length` bytes from the current stream and property to determine whether the current instance supports reading. @@ -1445,18 +1457,16 @@ If the operation is canceled before it completes, the returned task contains the The buffer to write the data into. - To be added. - The byte offset in at which to begin writing data from the Deflate stream. + The buffer to write the data into. + The byte offset at which to begin writing data from the Deflate stream. The maximum number of bytes to read. The token to monitor for cancellation requests. The default value is . Asynchronously reads a sequence of bytes from the current Deflate stream, writes them to a byte array, advances the position within the Deflate stream by the number of bytes read, and monitors cancellation requests. - A task that represents the asynchronous read operation, which wraps the total number of bytes read into the . The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the Deflate stream has been reached. + A task that represents the asynchronous read operation, which wraps the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the Deflate stream has been reached. property to determine whether the current instance supports reading. @@ -1504,8 +1514,6 @@ This method stores in the task it returns all non-usage exceptions that the meth property to determine whether the current instance supports reading. ]]> @@ -1648,8 +1656,6 @@ Use the property to determ property to determine whether the current instance supports writing. Use the method to write asynchronously to the current stream. If the write operation is successful, the position within the Deflate stream advances by the number of bytes written. If an exception occurs, the position within the Deflate stream remains unchanged. @@ -1706,20 +1712,19 @@ If the write operation is successful, the position within the Deflate stream adv The buffer that contains the data to compress. - To be added. - The byte offset in from which the bytes will be read. + The buffer that contains the data to compress. + The byte offset from which the bytes will be read. The maximum number of bytes to write. Writes compressed bytes to the underlying stream from the specified byte array. - and methods. - - :::code language="csharp" source="~/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs" id="Snippet1"::: - :::code language="fsharp" source="~/snippets/fsharp/System.IO.Compression/Deflate/MemoryWriteReadExample.fs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/MemoryWriteReadExample.vb" id="Snippet1"::: - + and methods. + +:::code language="csharp" source="~/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs" id="Snippet1"::: +:::code language="fsharp" source="~/snippets/fsharp/System.IO.Compression/Deflate/MemoryWriteReadExample.fs" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.IO.Compression/Deflate/MemoryWriteReadExample.vb" id="Snippet1"::: + ]]> @@ -1769,9 +1774,7 @@ If the write operation is successful, the position within the Deflate stream adv property to determine whether the current instance supports writing. @@ -1826,8 +1829,8 @@ If the operation is canceled before it completes, the returned task contains the The buffer that contains the data to compress. - To be added. - The zero-based byte offset in from which to begin copying bytes to the Deflate stream. + The buffer that contains the data to compress. + The zero-based byte offset from which to begin copying bytes to the Deflate stream. The maximum number of bytes to write. The token to monitor for cancellation requests. The default value is . Asynchronously writes compressed bytes to the underlying Deflate stream from the specified byte array. @@ -1835,9 +1838,7 @@ If the operation is canceled before it completes, the returned task contains the property to determine whether the current instance supports writing. From 2faf720bcf24f8ab2fef76d71edb19f9370072a1 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 18 Mar 2024 15:35:16 -0700 Subject: [PATCH 05/12] add warnings about breaking change --- xml/System.IO.Compression/DeflateStream.xml | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/xml/System.IO.Compression/DeflateStream.xml b/xml/System.IO.Compression/DeflateStream.xml index 08625d3b67f..3370d4c0a9e 100644 --- a/xml/System.IO.Compression/DeflateStream.xml +++ b/xml/System.IO.Compression/DeflateStream.xml @@ -458,6 +458,9 @@ You use this constructor when you want to specify whether compression efficiency [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). + Starting with .NET Framework 4.5, you can perform asynchronous read operations by using the method. The method is still available in current versions 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](/dotnet/standard/io/asynchronous-file-i-o). Pass the return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. You can do this either by using the same code that called or in a callback passed to . @@ -1262,7 +1265,8 @@ This method stores in the task it returns all non-usage exceptions that the meth [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). Use the property to determine whether the current instance supports reading. Use the method to read asynchronously from the current stream. @@ -1330,7 +1334,8 @@ Use for reading primitive data types. [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). The following example shows how to compress and decompress bytes by using the and methods. @@ -1402,6 +1407,9 @@ The following example shows how to compress and decompress bytes by using the [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). + The `ReadAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. Use the property to determine whether the current instance supports reading. @@ -1466,6 +1474,9 @@ If the operation is canceled before it completes, the returned task contains the [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). + The `ReadAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. Use the property to determine whether the current instance supports reading. From cba6e6d1c9fe2854c12ee1c4aab7b439ae4937a3 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 18 Mar 2024 15:42:34 -0700 Subject: [PATCH 06/12] update snippets --- .../Deflate/Deflate.csproj | 3 +-- .../Deflate/FileCompressionLevelExample.cs | 12 ++++++------ .../Deflate/FileCompressionModeExample.cs | 16 ++++++++-------- .../Deflate/MemoryWriteReadExample.cs | 18 +++++++++++++----- .../System.IO.Compression/Deflate/Program.cs | 9 +++++++++ .../GZip/MemoryWriteReadExample.cs | 2 +- 6 files changed, 38 insertions(+), 22 deletions(-) create mode 100644 snippets/csharp/System.IO.Compression/Deflate/Program.cs diff --git a/snippets/csharp/System.IO.Compression/Deflate/Deflate.csproj b/snippets/csharp/System.IO.Compression/Deflate/Deflate.csproj index c32f9c0eba6..f432dbe7e6f 100644 --- a/snippets/csharp/System.IO.Compression/Deflate/Deflate.csproj +++ b/snippets/csharp/System.IO.Compression/Deflate/Deflate.csproj @@ -2,9 +2,8 @@ Exe - net6.0 + net8.0 enable - FileCompressionModeExample diff --git a/snippets/csharp/System.IO.Compression/Deflate/FileCompressionLevelExample.cs b/snippets/csharp/System.IO.Compression/Deflate/FileCompressionLevelExample.cs index 99397a2ad77..f448e11facf 100644 --- a/snippets/csharp/System.IO.Compression/Deflate/FileCompressionLevelExample.cs +++ b/snippets/csharp/System.IO.Compression/Deflate/FileCompressionLevelExample.cs @@ -9,7 +9,7 @@ public static class FileCompressionLevelExample private const string OriginalFileName = "original.txt"; private const string CompressedFileName = "compressed.dfl"; - public static void Main() + public static void Run() { CreateFileToCompress(); CompressFile(); @@ -18,8 +18,8 @@ public static void Main() /* Output: - The original file 'original.txt' weighs 445 bytes. - The compressed file 'compressed.dfl' weighs 259 bytes. + The original file 'original.txt' is 445 bytes. + The compressed file 'compressed.dfl' is 259 bytes. */ } @@ -37,9 +37,9 @@ private static void PrintResults() { long originalSize = new FileInfo(OriginalFileName).Length; long compressedSize = new FileInfo(CompressedFileName).Length; - - Console.WriteLine($"The original file '{OriginalFileName}' weighs {originalSize} bytes."); - Console.WriteLine($"The compressed file '{CompressedFileName}' weighs {compressedSize} bytes."); + + Console.WriteLine($"The original file '{OriginalFileName}' is {originalSize} bytes."); + Console.WriteLine($"The compressed file '{CompressedFileName}' is {compressedSize} bytes."); } private static void DeleteFiles() diff --git a/snippets/csharp/System.IO.Compression/Deflate/FileCompressionModeExample.cs b/snippets/csharp/System.IO.Compression/Deflate/FileCompressionModeExample.cs index 0470bc09d54..3fd73da2bf3 100644 --- a/snippets/csharp/System.IO.Compression/Deflate/FileCompressionModeExample.cs +++ b/snippets/csharp/System.IO.Compression/Deflate/FileCompressionModeExample.cs @@ -10,7 +10,7 @@ public static class FileCompressionModeExample private const string CompressedFileName = "compressed.dfl"; private const string DecompressedFileName = "decompressed.txt"; - public static void Main() + public static void Run() { CreateFileToCompress(); CompressFile(); @@ -21,11 +21,11 @@ public static void Main() /* Output: - The original file 'original.txt' weighs 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + The original file 'original.txt' is 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." - The compressed file 'compressed.dfl' weighs 265 bytes. + The compressed file 'compressed.dfl' is 265 bytes. - The decompressed file 'decompressed.txt' weighs 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + The decompressed file 'decompressed.txt' is 445 bytes. Contents: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." */ } @@ -52,10 +52,10 @@ private static void PrintResults() long originalSize = new FileInfo(OriginalFileName).Length; long compressedSize = new FileInfo(CompressedFileName).Length; long decompressedSize = new FileInfo(DecompressedFileName).Length; - - Console.WriteLine($"The original file '{OriginalFileName}' weighs {originalSize} bytes. Contents: \"{File.ReadAllText(OriginalFileName)}\""); - Console.WriteLine($"The compressed file '{CompressedFileName}' weighs {compressedSize} bytes."); - Console.WriteLine($"The decompressed file '{DecompressedFileName}' weighs {decompressedSize} bytes. Contents: \"{File.ReadAllText(DecompressedFileName)}\""); + + Console.WriteLine($"The original file '{OriginalFileName}' is {originalSize} bytes. Contents: \"{File.ReadAllText(OriginalFileName)}\""); + Console.WriteLine($"The compressed file '{CompressedFileName}' is {compressedSize} bytes."); + Console.WriteLine($"The decompressed file '{DecompressedFileName}' is {decompressedSize} bytes. Contents: \"{File.ReadAllText(DecompressedFileName)}\""); } private static void DeleteFiles() diff --git a/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs b/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs index dcea395fccd..9edadf8d345 100644 --- a/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs +++ b/snippets/csharp/System.IO.Compression/Deflate/MemoryWriteReadExample.cs @@ -9,7 +9,7 @@ public static class MemoryWriteReadExample private const string Message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; private static readonly byte[] s_messageBytes = Encoding.ASCII.GetBytes(Message); - public static void Main() + public static void Run() { Console.WriteLine($"The original string length is {s_messageBytes.Length} bytes."); using var stream = new MemoryStream(); @@ -35,10 +35,18 @@ private static int DecompressStreamToBytes(Stream stream) { stream.Position = 0; int bufferSize = 512; - byte[] decompressedBytes = new byte[bufferSize]; - using var decompressor = new DeflateStream(stream, CompressionMode.Decompress); - int length = decompressor.Read(decompressedBytes, 0, bufferSize); - return length; + byte[] buffer = new byte[bufferSize]; + using var deflateStream = new DeflateStream(stream, CompressionMode.Decompress); + + int totalRead = 0; + while (totalRead < buffer.Length) + { + int bytesRead = deflateStream.Read(buffer.AsSpan(totalRead)); + if (bytesRead == 0) break; + totalRead += bytesRead; + } + + return totalRead; } } // diff --git a/snippets/csharp/System.IO.Compression/Deflate/Program.cs b/snippets/csharp/System.IO.Compression/Deflate/Program.cs new file mode 100644 index 00000000000..d7835cb58e1 --- /dev/null +++ b/snippets/csharp/System.IO.Compression/Deflate/Program.cs @@ -0,0 +1,9 @@ +class Program +{ + public static void Main() + { + MemoryWriteReadExample.Run(); + //FileCompressionLevelExample.Run(); + //FileCompressionModeExample.Run(); + } +} diff --git a/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs b/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs index 64c3721429d..3e38d601957 100644 --- a/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs +++ b/snippets/csharp/System.IO.Compression/GZip/MemoryWriteReadExample.cs @@ -41,7 +41,7 @@ private static int DecompressStreamToBytes(Stream stream) int totalRead = 0; while (totalRead < buffer.Length) { - int bytesRead = gzipStream.Read(buffer, totalRead, buffer.Length - totalRead); + int bytesRead = gzipStream.Read(buffer.AsSpan(totalRead)); if (bytesRead == 0) break; totalRead += bytesRead; } From 4fb8361fb6eebc3768a0194623c8738cb168ab67 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 19 Mar 2024 13:40:08 -0700 Subject: [PATCH 07/12] initial cleanup of cryptostream --- .../{fileexample.cs => CryptoStream.cs} | 76 ++- .../CryptoStream/Overview/CryptoStream.vb} | 64 ++- .../CryptoStream/Overview/project.vbproj | 8 + .../CryptoStream.xml | 436 ++++++++---------- 4 files changed, 269 insertions(+), 315 deletions(-) rename snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/{fileexample.cs => CryptoStream.cs} (53%) rename snippets/visualbasic/{VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb => System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb} (69%) create mode 100644 snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/project.vbproj diff --git a/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/fileexample.cs b/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs similarity index 53% rename from snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/fileexample.cs rename to snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs index f69b8ed186e..5da99db31ff 100644 --- a/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/fileexample.cs +++ b/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs @@ -3,31 +3,29 @@ using System.IO; using System.Security.Cryptography; -namespace RijndaelManaged_Example +namespace AesManaged_Example { - class RijndaelExample + class AesExample { public static void Main() { try { - string original = "Here is some data to encrypt!"; - // Create a new instance of the Rijndael - // class. This generates a new key and initialization - // vector (IV). - using (Rijndael myRijndael = Rijndael.Create()) + // Create a new instance of the Aes class. + // This generates a new key and initialization vector (IV). + using (Aes myAes = Aes.Create()) { // Encrypt the string to an array of bytes. - byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV); + byte[] encrypted = EncryptStringToBytes(original, myAes.Key, myAes.IV); // Decrypt the bytes to a string. - string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV); + string roundtrip = DecryptStringFromBytes(encrypted, myAes.Key, myAes.IV); - //Display the original data and the decrypted data. + // Display the original data and the decrypted data. Console.WriteLine("Original: {0}", original); - Console.WriteLine("Round Trip: {0}", roundtrip); + Console.WriteLine("Round trip: {0}", roundtrip); } } catch (Exception e) @@ -35,36 +33,36 @@ public static void Main() Console.WriteLine("Error: {0}", e.Message); } } + // static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) { // Check arguments. if (plainText == null || plainText.Length <= 0) - throw new ArgumentNullException("plainText"); + throw new ArgumentNullException(nameof(plainText)); if (Key == null || Key.Length <= 0) - throw new ArgumentNullException("Key"); + throw new ArgumentNullException(nameof(Key)); if (IV == null || IV.Length <= 0) - throw new ArgumentNullException("IV"); + throw new ArgumentNullException(nameof(IV)); byte[] encrypted; - // Create an Rijndael object - // with the specified key and IV. - using (Rijndael rijAlg = Rijndael.Create()) + + // Create a Aes object with the specified key and IV. + using (Aes aesAlg = Aes.Create()) { - rijAlg.Key = Key; - rijAlg.IV = IV; + aesAlg.Key = Key; + aesAlg.IV = IV; // Create an encryptor to perform the stream transform. - ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); + ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. - using (MemoryStream msEncrypt = new MemoryStream()) + using (MemoryStream msEncrypt = new()) { - using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) + using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write)) { - using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) + using (StreamWriter swEncrypt = new(csEncrypt)) { - - //Write all data to the stream. + // Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); @@ -82,32 +80,30 @@ static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) { // Check arguments. if (cipherText == null || cipherText.Length <= 0) - throw new ArgumentNullException("cipherText"); + throw new ArgumentNullException(nameof(cipherText)); if (Key == null || Key.Length <= 0) - throw new ArgumentNullException("Key"); + throw new ArgumentNullException(nameof(Key)); if (IV == null || IV.Length <= 0) - throw new ArgumentNullException("IV"); + throw new ArgumentNullException(nameof(IV)); - // Declare the string used to hold - // the decrypted text. + // Declare the string used to hold the decrypted text. string plaintext = null; - // Create an Rijndael object - // with the specified key and IV. - using (Rijndael rijAlg = Rijndael.Create()) + // Create a Aes object with the specified key and IV. + using (Aes aesAlg = Aes.Create()) { - rijAlg.Key = Key; - rijAlg.IV = IV; + aesAlg.Key = Key; + aesAlg.IV = IV; // Create a decryptor to perform the stream transform. - ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); + ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. - using (MemoryStream msDecrypt = new MemoryStream(cipherText)) + using (MemoryStream msDecrypt = new(cipherText)) { - using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) + using (CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read)) { - using (StreamReader srDecrypt = new StreamReader(csDecrypt)) + using (StreamReader srDecrypt = new(csDecrypt)) { // Read the decrypted bytes from the decrypting stream @@ -123,4 +119,4 @@ static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) // } } -// \ No newline at end of file +// diff --git a/snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb b/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb similarity index 69% rename from snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb rename to snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb index 73d17ce9c9f..d731483d1fb 100644 --- a/snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb +++ b/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb @@ -2,25 +2,21 @@ Imports System.IO Imports System.Security.Cryptography - - -Class RijndaelExample +Class AesExample Public Shared Sub Main() Try - Dim original As String = "Here is some data to encrypt!" - ' Create a new instance of the Rijndael - ' class. This generates a new key and initialization - ' vector (IV). - Using myRijndael = Rijndael.Create() + ' Create a new instance of the Aes class. + ' This generates a new key and initialization vector (IV). + Using myAes = Aes.Create() ' Encrypt the string to an array of bytes. - Dim encrypted As Byte() = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV) + Dim encrypted As Byte() = EncryptStringToBytes(original, myAes.Key, myAes.IV) ' Decrypt the bytes to a string. - Dim roundtrip As String = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV) + Dim roundtrip As String = DecryptStringFromBytes(encrypted, myAes.Key, myAes.IV) 'Display the original data and the decrypted data. Console.WriteLine("Original: {0}", original) @@ -29,37 +25,36 @@ Class RijndaelExample Catch e As Exception Console.WriteLine("Error: {0}", e.Message) End Try - End Sub ' Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte() ' Check arguments. If plainText Is Nothing OrElse plainText.Length <= 0 Then - Throw New ArgumentNullException("plainText") + Throw New ArgumentNullException(NameOf(plainText)) End If If Key Is Nothing OrElse Key.Length <= 0 Then - Throw New ArgumentNullException("Key") + Throw New ArgumentNullException(NameOf(Key)) End If If IV Is Nothing OrElse IV.Length <= 0 Then - Throw New ArgumentNullException("IV") + Throw New ArgumentNullException(NameOf(IV)) End If Dim encrypted() As Byte - ' Create an Rijndael object - ' with the specified key and IV. - Using rijAlg = Rijndael.Create() - rijAlg.Key = Key - rijAlg.IV = IV + ' Create an Aes object with the specified key and IV. + Using aesAlg = Aes.Create() + + aesAlg.Key = Key + aesAlg.IV = IV ' Create an encryptor to perform the stream transform. - Dim encryptor As ICryptoTransform = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV) + Dim encryptor As ICryptoTransform = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV) ' Create the streams used for encryption. Using msEncrypt As New MemoryStream() Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write) Using swEncrypt As New StreamWriter(csEncrypt) - 'Write all data to the stream. + ' Write all data to the stream. swEncrypt.Write(plainText) End Using encrypted = msEncrypt.ToArray() @@ -77,35 +72,30 @@ Class RijndaelExample Shared Function DecryptStringFromBytes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String ' Check arguments. If cipherText Is Nothing OrElse cipherText.Length <= 0 Then - Throw New ArgumentNullException("cipherText") + Throw New ArgumentNullException(NameOf(cipherText)) End If If Key Is Nothing OrElse Key.Length <= 0 Then - Throw New ArgumentNullException("Key") + Throw New ArgumentNullException(NameOf(Key)) End If If IV Is Nothing OrElse IV.Length <= 0 Then - Throw New ArgumentNullException("IV") + Throw New ArgumentNullException(NameOf(IV)) End If - ' Declare the string used to hold - ' the decrypted text. + + ' Declare the string used to hold the decrypted text. Dim plaintext As String = Nothing - ' Create an Rijndael object - ' with the specified key and IV. - Using rijAlg = Rijndael.Create() - rijAlg.Key = Key - rijAlg.IV = IV + ' Create an Aes object with the specified key and IV. + Using aesAlg = Aes.Create() + aesAlg.Key = Key + aesAlg.IV = IV ' Create a decryptor to perform the stream transform. - Dim decryptor As ICryptoTransform = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV) + Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV) ' Create the streams used for decryption. Using msDecrypt As New MemoryStream(cipherText) - Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read) - Using srDecrypt As New StreamReader(csDecrypt) - - ' Read the decrypted bytes from the decrypting stream ' and place them in a string. plaintext = srDecrypt.ReadToEnd() @@ -119,4 +109,4 @@ Class RijndaelExample End Function 'DecryptStringFromBytes End Class ' -' \ No newline at end of file +' diff --git a/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/project.vbproj b/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/project.vbproj new file mode 100644 index 00000000000..d50c0e10aeb --- /dev/null +++ b/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/project.vbproj @@ -0,0 +1,8 @@ + + + + Exe + net8.0 + + + \ No newline at end of file diff --git a/xml/System.Security.Cryptography/CryptoStream.xml b/xml/System.Security.Cryptography/CryptoStream.xml index 61816b8f860..22478873436 100644 --- a/xml/System.Security.Cryptography/CryptoStream.xml +++ b/xml/System.Security.Cryptography/CryptoStream.xml @@ -67,31 +67,24 @@ Defines a stream that links data streams to cryptographic transformations. - . Any cryptographic objects that implement can be chained together with any objects that implement , so the streamed output from one object can be fed into the input of another object. The intermediate result (the output from the first object) does not need to be stored separately. - -> [!IMPORTANT] -> - This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly by calling its method, which in turn calls its implementation. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. -> - When `Stream.Read` or `Stream.ReadAsync` is called with a buffer of length `N`, the operation completes when either: -> -> - At least one byte has been read from the stream, or -> - The underlying stream that it wraps returns 0 from a call to `Read`, indicating no more data is available. -> -> Also, when `Stream.Read` or `Stream.ReadAsync` is called with a buffer of length 0, the operation succeeds once a call with a non-zero buffer would succeed. - -Prior to .NET 6, `Stream.Read` and `Stream.ReadAsync` did not return until `N` bytes had been read from the stream or the underlying stream returned 0 from a call to `Read`. If your code assumed they wouldn't return until all `N` bytes were read, it could fail to read all the content. For more information, see [Partial and zero-byte reads in streams](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). - -You should always explicitly close your object after you are done using it by calling the method. Doing so flushes the underlying stream and causes all remaining blocks of data to be processed by the object. However, if an exception occurs before you call the method, the object might not be closed. To ensure that the method always gets called, place your call to the method within the `finally` block of a `try`/`catch` statement. - -## Examples - The following example demonstrates how to use a to encrypt a string. This method uses class with the specified and initialization vector (). - - :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/fileexample.cs" interactive="try-dotnet" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb" id="Snippet1"::: - + . Any cryptographic objects that implement can be chained together with any objects that implement , so the streamed output from one object can be fed into the input of another object. The intermediate result (the output from the first object) does not need to be stored separately. + +> [!IMPORTANT] +> In .NET 6 and later versions, when `Stream.Read` or `Stream.ReadAsync` is called with a buffer of length `N`, the operation completes when either at least 1 byte has been read from the stream, or the underlying stream that it wraps returns 0 from a call to `Read`, indicating no more data is available. Prior to .NET 6, `Stream.Read` and `Stream.ReadAsync` did not return until all `N` bytes had been read from the stream or the underlying stream returned 0 from a call to `Read`. If your code assumes the `Read` methods won't return until all `N` bytes have been read, it could fail to read all the content. For more information, see [Partial and zero-byte reads in streams](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). + +You should always explicitly close your object after you're finished using it by calling the method. Doing so flushes the underlying stream and causes all remaining blocks of data to be processed by the object. However, if an exception occurs before you call the method, the object might not be closed. To ensure that the method always gets called, place your call to the method within the `finally` block of a `try`/`catch` statement. + +This type implements the interface. When you've finished using the type, you should dispose of it either directly or indirectly by calling its method, which in turn calls its implementation. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). + +## Examples + +The following example demonstrates how to use a to encrypt a string. This method uses class with the specified and initialization vector (). + +:::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs" interactive="try-dotnet" id="Snippet1"::: +:::code language="vb" source="~/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb" id="Snippet1"::: + ]]> Cryptographic Services @@ -144,11 +137,10 @@ You should always explicitly close your One of the values. Initializes a new instance of the class with a target data stream, the transformation to use, and the mode of the stream. - can be passed into the `stream` parameter. Any object that implements (such as ) can be passed into the `transform` parameter. - + can be passed into the `stream` parameter. Any object that implements (such as ) can be passed into the `transform` parameter. + ]]> @@ -263,21 +255,20 @@ You should always explicitly close your Begins an asynchronous read operation. (Consider using instead.) An that represents the asynchronous read, which could still be pending. - and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - Pass the `IAsyncResult` return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . You can do this either by using the same code that called `BeginRead` or in a callback passed to `BeginRead`. - - The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. - - Multiple simultaneous asynchronous requests render the request completion order uncertain. - - Use the property to determine whether the current instance supports reading. - - If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginRead`. Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndRead`. - + and to implement asynchronous I/O operations. These methods are still available in current versions to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + +Pass the `IAsyncResult` return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . You can do this either by using the same code that called `BeginRead` or in a callback passed to `BeginRead`. + +The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. + +Multiple simultaneous asynchronous requests render the request completion order uncertain. + +Use the property to determine whether the current instance supports reading. + +If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginRead`. Errors that occur during an asynchronous read request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndRead`. + ]]> Attempted an asynchronous read past the end of the stream, or a disk error occurred. @@ -345,21 +336,20 @@ You should always explicitly close your Begins an asynchronous write operation. (Consider using instead.) An that represents the asynchronous write, which could still be pending. - and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - Pass the `IAsyncResult` returned by the current method to to ensure that the write completes and frees resources appropriately. must be called once for every call to . You can do this either by using the same code that called `BeginWrite` or in a callback passed to `BeginWrite`. If an error occurs during an asynchronous write, an exception will not be thrown until `EndWrite` is called with the `IAsyncResult` returned by this method. - - If a stream is writable, writing at the end of the stream expands the stream. - - The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. - - Use the property to determine whether the current instance supports writing. - - If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginWrite`. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndWrite`. - + and to implement asynchronous I/O operations. These methods are still available in current versions to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + +Pass the `IAsyncResult` returned by the current method to to ensure that the write completes and frees resources appropriately. must be called once for every call to . You can do this either by using the same code that called `BeginWrite` or in a callback passed to `BeginWrite`. If an error occurs during an asynchronous write, an exception will not be thrown until `EndWrite` is called with the `IAsyncResult` returned by this method. + +If a stream is writable, writing at the end of the stream expands the stream. + +The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. + +Use the property to determine whether the current instance supports writing. + +If a stream is closed or you pass an invalid argument, exceptions are thrown immediately from `BeginWrite`. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and throw exceptions when calling `EndWrite`. + ]]> Attempted an asynchronous write past the end of the stream, or a disk error occurred. @@ -456,11 +446,10 @@ You should always explicitly close your Gets a value indicating whether you can seek within the current . Always . - , so this method always returns `false`. - + , so this method always returns `false`. + ]]> Cryptographic Services @@ -553,13 +542,12 @@ You should always explicitly close your Releases all resources used by the . - implementation. - - Calling `Dispose` allows the resources used by the to be reallocated for other purposes. For more information about `Dispose`, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) - + implementation. + +Calling `Dispose` allows the resources used by the to be reallocated for other purposes. For more information about `Dispose`, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). + ]]> Cryptographic Services @@ -631,22 +619,20 @@ You should always explicitly close your The size, in bytes, of the buffer to use for reading from the underlying stream. This value must be greater than zero. The default size is 81920 bytes. Reads the bytes from the underlying stream, applies the relevant cryptographic transforms, and writes the result to the destination stream. - is . is negative or zero. - The current stream does not support reading. - - -or- - + The current stream does not support reading. + + -or- + does not support writing. Either the current stream or were closed before the method was called. An I/O error occurred. @@ -693,14 +679,12 @@ Copying begins at the current position in the current stream, and does not reset Asynchronously reads the bytes from the underlying stream, applies the relevant cryptographic transforms, and writes the result to the destination stream. A task that represents the asynchronous copy operation. - , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - + , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + ]]> @@ -765,20 +749,19 @@ Copying begins at the current position in the current stream, and does not reset to release both managed and unmanaged resources; to release only unmanaged resources. Releases the unmanaged resources used by the and optionally releases the managed resources. - method, if it has been overridden. `Dispose()` invokes the protected `Dispose(Boolean)` method with the disposing parameter set to `true`. `Finalize` invokes `Dispose` with disposing set to `false`. - - When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. - + method, if it has been overridden. `Dispose()` invokes the protected `Dispose(Boolean)` method with the disposing parameter set to `true`. `Finalize` invokes `Dispose` with disposing set to `false`. + +When the `disposing` parameter is `true`, this method releases all resources held by any managed objects that this references. This method invokes the `Dispose()` method of each referenced object. + ]]> - can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). - - For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). + can be called multiple times by other objects. When overriding , be careful not to reference objects that have been previously disposed in an earlier call to . For more information about how to implement , see [Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose). + +For more information about and , see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). Cryptographic Services @@ -816,15 +799,14 @@ Copying begins at the current position in the current stream, and does not reset Asynchronously releases the unmanaged resources used by the . A task that represents the asynchronous dispose operation. - method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. - - This method disposes the stream by writing any changes to the backing store and closing the stream to release resources. - - Calling `DisposeAsync` allows the resources used by the to be reallocated for other purposes. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). - + method enables you to perform a resource-intensive dispose operation without blocking the main thread. This performance consideration is particularly important in desktop apps where a time-consuming stream operation can block the UI thread and make the app appear as if it's not working. The async methods are used in conjunction with the `async` and `await` keywords in Visual Basic and C#. + +This method disposes the stream by writing any changes to the backing store and closing the stream to release resources. + +Calling `DisposeAsync` allows the resources used by the to be reallocated for other purposes. For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged). + ]]> @@ -865,25 +847,24 @@ Copying begins at the current position in the current stream, and does not reset Waits for the pending asynchronous read to complete. (Consider using instead.) The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one byte is available. - and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - Call `EndRead` to determine how many bytes were read from the stream. - - `EndRead` can be called once on every from . - - This method blocks until the I/O operation has completed. - + and to implement asynchronous I/O operations. These methods are still available in current versions to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + +Call `EndRead` to determine how many bytes were read from the stream. + +`EndRead` can be called once on every from . + +This method blocks until the I/O operation has completed. + ]]> is . - A handle to the pending read operation is not available. - - -or- - + A handle to the pending read operation is not available. + + -or- + The pending operation does not support reading. did not originate from a method on the current stream. @@ -925,23 +906,22 @@ Copying begins at the current position in the current stream, and does not reset A reference to the outstanding asynchronous I/O request. Ends an asynchronous write operation. (Consider using instead.) - and to implement asynchronous I/O operations. These methods are still available in .NET to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. - - `EndWrite` must be called exactly once on every from . - - This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to `EndWrite`. Exceptions thrown by the thread pool thread will not be visible when calling `EndWrite`. - + and to implement asynchronous I/O operations. These methods are still available in current versions to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. + +`EndWrite` must be called exactly once on every from . + +This method blocks until the I/O operation has completed. Errors that occur during an asynchronous write request, such as a disk failure during the I/O request, occur on the thread pool thread and become visible upon a call to `EndWrite`. Exceptions thrown by the thread pool thread will not be visible when calling `EndWrite`. + ]]> is . - A handle to the pending write operation is not available. - - -or- - + A handle to the pending write operation is not available. + + -or- + The pending operation does not support writing. did not originate from a method on the current stream. @@ -1020,14 +1000,13 @@ Copying begins at the current position in the current stream, and does not reset Clears all buffers for the current stream and causes any buffered data to be written to the underlying device. - or . Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. - -> [!NOTE] -> You should call either the method or the method to complete flushing the buffer. - + or . Setting to `true` means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters. + +> [!NOTE] +> You should call either the method or the method to complete flushing the buffer. + ]]> Cryptographic Services @@ -1077,15 +1056,14 @@ Copying begins at the current position in the current stream, and does not reset Clears all buffers for the current stream asynchronously, causes any buffered data to be written to the underlying device, and monitors cancellation requests. A task that represents the asynchronous flush operation. - with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). - - If the operation is canceled before it completes, the returned task contains the value for the property. - - This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - + with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). + +If the operation is canceled before it completes, the returned task contains the value for the property. + +This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + ]]> The stream has been disposed. @@ -1134,18 +1112,17 @@ Copying begins at the current position in the current stream, and does not reset Updates the underlying data source or repository with the current state of the buffer, then clears the buffer. - method will call . If you do not call , call to complete flushing the buffer. Call only when all stream activity is complete. - + method will call . If you do not call , call to complete flushing the buffer. Call only when all stream activity is complete. + ]]> The key is corrupt which can cause invalid padding to the stream. - The current stream is not writable. - - -or- - + The current stream is not writable. + + -or- + The final block has already been transformed. Cryptographic Services @@ -1226,11 +1203,10 @@ Copying begins at the current position in the current stream, and does not reset if the final block has been flushed; otherwise, . - method is called. - + method is called. + ]]> @@ -1277,11 +1253,10 @@ Copying begins at the current position in the current stream, and does not reset Gets the length in bytes of the stream. This property is not supported. - , and cannot be used. - + , and cannot be used. + ]]> This property is not supported. @@ -1330,11 +1305,10 @@ Copying begins at the current position in the current stream, and does not reset Gets or sets the position within the current stream. This property is not supported. - , and cannot be used. - + , and cannot be used. + ]]> This property is not supported. @@ -1399,11 +1373,8 @@ Copying begins at the current position in the current stream, and does not reset The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream has been reached. To be added. The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is write only. - The parameter is less than zero. - - -or- - - The parameter is less than zero. + + or is less than zero. The sum of the and parameters is longer than the length of the buffer. Cryptographic Services @@ -1450,7 +1421,7 @@ Copying begins at the current position in the current stream, and does not reset Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of its property contains the total number of bytes read into the buffer. The result value can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or it can be 0 (zero) if the end of the stream has been reached. To be added. - The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is write only. + The associated with the current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that's write only. The cancellation token was canceled. This exception is stored into the returned task. @@ -1505,15 +1476,14 @@ Copying begins at the current position in the current stream, and does not reset Reads a sequence of bytes from the current stream asynchronously, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of the task object's parameter contains the total number of bytes read into the buffer. The result can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if the end of the stream has been reached. - with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). - - If the operation is canceled before it completes, the returned task contains the value for the property. - - This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - + with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). + +If the operation is canceled before it completes, the returned task contains the value for the property. + +This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + ]]> @@ -1524,8 +1494,8 @@ Copying begins at the current position in the current stream, and does not reset The stream does not support reading. The stream has been disposed. The stream is currently in use by a previous read operation. - Cancellation The cancellation token was canceled. This exception is stored into the returned task. + Cancellation in managed threads @@ -1562,13 +1532,12 @@ Copying begins at the current position in the current stream, and does not reset Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. The unsigned byte cast to an , or -1 if at the end of the stream. - property to determine whether the current instance supports reading. - - Attempts to manipulate the stream after the stream has been closed could throw an . - + property to determine whether the current instance supports reading. + +If you attempt to manipulate the stream after the stream has been closed, an might be thrown. + ]]> The stream does not support reading. @@ -1623,11 +1592,10 @@ Copying begins at the current position in the current stream, and does not reset Sets the position within the current stream. This method is not supported. - , and cannot be used. - + , and cannot be used. + ]]> This method is not supported. @@ -1679,11 +1647,10 @@ Copying begins at the current position in the current stream, and does not reset The desired length of the current stream in bytes. Sets the length of the current stream. - , and cannot be used. - + , and cannot be used. + ]]> This property exists only to support inheritance from , and cannot be used. @@ -1721,12 +1688,10 @@ Copying begins at the current position in the current stream, and does not reset Releases the resources used by the current instance of the class. - instance is cast to an interface. - + instance is cast to an interface. + ]]> @@ -1788,11 +1753,8 @@ This member is an explicit interface member implementation. It can be used only Writes a sequence of bytes to the current and advances the current position within the stream by the number of bytes written. To be added. The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is read only. - The parameter is less than zero. - - -or- - - The parameter is less than zero. + + or is less than zero. The sum of the and parameters is longer than the length of the buffer. Cryptographic Services @@ -1839,9 +1801,9 @@ This member is an explicit interface member implementation. It can be used only Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. To be added. - The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is read only. - + The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is read only. The cancellation token was canceled. This exception is stored into the returned task. + @@ -1894,15 +1856,14 @@ This member is an explicit interface member implementation. It can be used only Writes a sequence of bytes to the current stream asynchronously, advances the current position within the stream by the number of bytes written, and monitors cancellation requests. A task that represents the asynchronous write operation. - with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). - - If the operation is canceled before it completes, the returned task contains the value for the property. - - This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . - + with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). + +If the operation is canceled before it completes, the returned task contains the value for the property. + +This method stores in the task it returns all non-usage exceptions that the method's synchronous counterpart can throw. If an exception is stored into the returned task, that exception will be thrown when the task is awaited. Usage exceptions, such as , are still thrown synchronously. For the stored exceptions, see the exceptions thrown by . + ]]> @@ -1953,11 +1914,10 @@ This member is an explicit interface member implementation. It can be used only The byte to write to the stream. Writes a byte to the current position in the stream and advances the position within the stream by one byte. - property to determine whether the current instance supports writing. - + property to determine whether the current instance supports writing. + ]]> An I/O error occurs. From 62520122f20445f55e20e87fd3d07155618dc338 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 19 Mar 2024 13:42:50 -0700 Subject: [PATCH 08/12] add related article links --- xml/System.IO.Compression/DeflateStream.xml | 1 + xml/System.IO.Compression/GZipStream.xml | 1 + 2 files changed, 2 insertions(+) diff --git a/xml/System.IO.Compression/DeflateStream.xml b/xml/System.IO.Compression/DeflateStream.xml index 3370d4c0a9e..abe468f4971 100644 --- a/xml/System.IO.Compression/DeflateStream.xml +++ b/xml/System.IO.Compression/DeflateStream.xml @@ -75,6 +75,7 @@ The following example shows how to use the + Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream diff --git a/xml/System.IO.Compression/GZipStream.xml b/xml/System.IO.Compression/GZipStream.xml index 75ec2d5c1ec..e5e879833f4 100644 --- a/xml/System.IO.Compression/GZipStream.xml +++ b/xml/System.IO.Compression/GZipStream.xml @@ -78,6 +78,7 @@ The following example shows how to use the When you inherit from , you must override the following members: , , and . + Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream From 7bd332987084611aae43c2463ef3157b41360efd Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 19 Mar 2024 14:14:34 -0700 Subject: [PATCH 09/12] code snippet touch ups --- .../CryptoStream/Overview/CryptoStream.cs | 167 +++++++++--------- .../CryptoStream/Overview/Project.csproj | 4 +- .../CryptoStream/Overview/CryptoStream.vb | 9 +- .../CryptoStream.xml | 20 ++- 4 files changed, 103 insertions(+), 97 deletions(-) diff --git a/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs b/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs index 5da99db31ff..4843ea5bb8a 100644 --- a/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs +++ b/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs @@ -3,120 +3,117 @@ using System.IO; using System.Security.Cryptography; -namespace AesManaged_Example +class AesExample { - class AesExample + public static void Main() { - public static void Main() + try { - try - { - string original = "Here is some data to encrypt!"; + string original = "Here is some data to encrypt!"; - // Create a new instance of the Aes class. - // This generates a new key and initialization vector (IV). - using (Aes myAes = Aes.Create()) - { - // Encrypt the string to an array of bytes. - byte[] encrypted = EncryptStringToBytes(original, myAes.Key, myAes.IV); + // Create a new instance of the Aes class. + // This generates a new key and initialization vector (IV). + using (Aes myAes = Aes.Create()) + { + // Encrypt the string to an array of bytes. + byte[] encrypted = EncryptStringToBytes(original, myAes.Key, myAes.IV); - // Decrypt the bytes to a string. - string roundtrip = DecryptStringFromBytes(encrypted, myAes.Key, myAes.IV); + // Decrypt the bytes to a string. + string roundtrip = DecryptStringFromBytes(encrypted, myAes.Key, myAes.IV); - // Display the original data and the decrypted data. - Console.WriteLine("Original: {0}", original); - Console.WriteLine("Round trip: {0}", roundtrip); - } - } - catch (Exception e) - { - Console.WriteLine("Error: {0}", e.Message); + // Display the original data and the decrypted data. + Console.WriteLine("Original: {0}", original); + Console.WriteLine("Round trip: {0}", roundtrip); } } + catch (Exception e) + { + Console.WriteLine("Error: {0}", e.Message); + } + } - // - static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) + // + static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) + { + // Check arguments. + if (plainText == null || plainText.Length <= 0) + throw new ArgumentNullException(nameof(plainText)); + if (Key == null || Key.Length <= 0) + throw new ArgumentNullException(nameof(Key)); + if (IV == null || IV.Length <= 0) + throw new ArgumentNullException(nameof(IV)); + byte[] encrypted; + + // Create a Aes object with the specified key and IV. + using (Aes aesAlg = Aes.Create()) { - // Check arguments. - if (plainText == null || plainText.Length <= 0) - throw new ArgumentNullException(nameof(plainText)); - if (Key == null || Key.Length <= 0) - throw new ArgumentNullException(nameof(Key)); - if (IV == null || IV.Length <= 0) - throw new ArgumentNullException(nameof(IV)); - byte[] encrypted; - - // Create a Aes object with the specified key and IV. - using (Aes aesAlg = Aes.Create()) - { - aesAlg.Key = Key; - aesAlg.IV = IV; + aesAlg.Key = Key; + aesAlg.IV = IV; - // Create an encryptor to perform the stream transform. - ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); + // Create an encryptor to perform the stream transform. + ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); - // Create the streams used for encryption. - using (MemoryStream msEncrypt = new()) + // Create the streams used for encryption. + using (MemoryStream msEncrypt = new()) + { + using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write)) { - using (CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write)) + using (StreamWriter swEncrypt = new(csEncrypt)) { - using (StreamWriter swEncrypt = new(csEncrypt)) - { - // Write all data to the stream. - swEncrypt.Write(plainText); - } - encrypted = msEncrypt.ToArray(); + // Write all data to the stream. + swEncrypt.Write(plainText); } + encrypted = msEncrypt.ToArray(); } } - - // Return the encrypted bytes from the memory stream. - return encrypted; } - // - // - static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) + // Return the encrypted bytes from the memory stream. + return encrypted; + } + // + + // + static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV) + { + // Check arguments. + if (cipherText == null || cipherText.Length <= 0) + throw new ArgumentNullException(nameof(cipherText)); + if (Key == null || Key.Length <= 0) + throw new ArgumentNullException(nameof(Key)); + if (IV == null || IV.Length <= 0) + throw new ArgumentNullException(nameof(IV)); + + // Declare the string used to hold the decrypted text. + string plaintext = null; + + // Create a Aes object with the specified key and IV. + using (Aes aesAlg = Aes.Create()) { - // Check arguments. - if (cipherText == null || cipherText.Length <= 0) - throw new ArgumentNullException(nameof(cipherText)); - if (Key == null || Key.Length <= 0) - throw new ArgumentNullException(nameof(Key)); - if (IV == null || IV.Length <= 0) - throw new ArgumentNullException(nameof(IV)); - - // Declare the string used to hold the decrypted text. - string plaintext = null; - - // Create a Aes object with the specified key and IV. - using (Aes aesAlg = Aes.Create()) - { - aesAlg.Key = Key; - aesAlg.IV = IV; + aesAlg.Key = Key; + aesAlg.IV = IV; - // Create a decryptor to perform the stream transform. - ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); + // Create a decryptor to perform the stream transform. + ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); - // Create the streams used for decryption. - using (MemoryStream msDecrypt = new(cipherText)) + // Create the streams used for decryption. + using (MemoryStream msDecrypt = new(cipherText)) + { + using (CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read)) { - using (CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read)) + using (StreamReader srDecrypt = new(csDecrypt)) { - using (StreamReader srDecrypt = new(csDecrypt)) - { - // Read the decrypted bytes from the decrypting stream - // and place them in a string. - plaintext = srDecrypt.ReadToEnd(); - } + // Read the decrypted bytes from the decrypting stream + // and place them in a string. + plaintext = srDecrypt.ReadToEnd(); } } } - - return plaintext; } - // + + return plaintext; } + // } // diff --git a/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/Project.csproj b/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/Project.csproj index c02dc5044e7..24f58ecd991 100644 --- a/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/Project.csproj +++ b/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/Project.csproj @@ -1,8 +1,8 @@ - Library - net6.0 + Exe + net8.0 \ No newline at end of file diff --git a/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb b/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb index d731483d1fb..cacccfccd59 100644 --- a/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb +++ b/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb @@ -66,10 +66,13 @@ Class AesExample Return encrypted End Function 'EncryptStringToBytes - ' + ' - Shared Function DecryptStringFromBytes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String + Shared Function DecryptStringFromBytes( + ByVal cipherText() As Byte, + ByVal Key() As Byte, + ByVal IV() As Byte) As String ' Check arguments. If cipherText Is Nothing OrElse cipherText.Length <= 0 Then Throw New ArgumentNullException(NameOf(cipherText)) @@ -107,6 +110,6 @@ Class AesExample Return plaintext End Function 'DecryptStringFromBytes + ' End Class -' ' diff --git a/xml/System.Security.Cryptography/CryptoStream.xml b/xml/System.Security.Cryptography/CryptoStream.xml index 22478873436..4d85f1305d6 100644 --- a/xml/System.Security.Cryptography/CryptoStream.xml +++ b/xml/System.Security.Cryptography/CryptoStream.xml @@ -80,7 +80,7 @@ This type implements the interface. When you've finish ## Examples -The following example demonstrates how to use a to encrypt a string. This method uses class with the specified and initialization vector (). +The following example demonstrates how to use a to encrypt a string. This method uses the class with the specified and initialization vector (). :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.cs" interactive="try-dotnet" id="Snippet1"::: :::code language="vb" source="~/snippets/visualbasic/System.Security.Cryptography/CryptoStream/Overview/CryptoStream.vb" id="Snippet1"::: @@ -257,6 +257,9 @@ Any object that derives from can be passed into the `str [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). + In .NET Framework 4 and earlier versions, you have to use methods such as and to implement asynchronous I/O operations. These methods are still available in current versions to support legacy code; however, the new async methods, such as , , , and , help you implement asynchronous I/O operations more easily. Pass the `IAsyncResult` return value to the method of the stream to determine how many bytes were read and to release operating system resources used for reading. must be called once for every call to . You can do this either by using the same code that called `BeginRead` or in a callback passed to `BeginRead`. @@ -1371,8 +1374,8 @@ This property exists only to support inheritance from , a The maximum number of bytes to be read from the current stream. Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero if the end of the stream has been reached. - To be added. - The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is write only. + Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream. + The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is write only. or is less than zero. The sum of the and parameters is longer than the length of the buffer. @@ -1420,10 +1423,10 @@ This property exists only to support inheritance from , a The token to monitor for cancellation requests. The default value is . Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests. A task that represents the asynchronous read operation. The value of its property contains the total number of bytes read into the buffer. The result value can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or it can be 0 (zero) if the end of the stream has been reached. - To be added. - The associated with the current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that's write only. - + Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream. + The associated with the current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that's write only. The cancellation token was canceled. This exception is stored into the returned task. + @@ -1478,6 +1481,9 @@ This property exists only to support inheritance from , a [!IMPORTANT] +> Starting in .NET 6, this method might not read as many bytes as were requested. For more information, see [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams). + You must preface your call to with the `await` (C#) or `Await` (Visual Basic) operator to suspend execution of the method until the task is complete. For more information, see [Asynchronous programming (C#)](/dotnet/csharp/async) or [Asynchronous programming with Async and Await (Visual Basic)](/dotnet/visual-basic/programming-guide/concepts/async/). If the operation is canceled before it completes, the returned task contains the value for the property. @@ -1752,7 +1758,7 @@ This member is an explicit interface member implementation. It can be used only The number of bytes to be written to the current stream. Writes a sequence of bytes to the current and advances the current position within the stream by the number of bytes written. To be added. - The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is read only. + The associated with current object does not match the underlying stream. For example, this exception is thrown when using with an underlying stream that is read only. or is less than zero. The sum of the and parameters is longer than the length of the buffer. From 51be02fbb9378252730ed71b046d8f4b87b673d5 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 19 Mar 2024 14:28:38 -0700 Subject: [PATCH 10/12] add end tag --- xml/System.IO.Compression/DeflateStream.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/xml/System.IO.Compression/DeflateStream.xml b/xml/System.IO.Compression/DeflateStream.xml index abe468f4971..f943fda0ebc 100644 --- a/xml/System.IO.Compression/DeflateStream.xml +++ b/xml/System.IO.Compression/DeflateStream.xml @@ -447,6 +447,7 @@ You use this constructor when you want to specify whether compression efficiency + The byte array to read the data into. The byte array to read the data into. From 98266ab85b98a026f7da4fa596b64c1a8190b870 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 19 Mar 2024 14:40:18 -0700 Subject: [PATCH 11/12] add end tag --- xml/System.IO.Compression/DeflateStream.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/xml/System.IO.Compression/DeflateStream.xml b/xml/System.IO.Compression/DeflateStream.xml index f943fda0ebc..b010c797969 100644 --- a/xml/System.IO.Compression/DeflateStream.xml +++ b/xml/System.IO.Compression/DeflateStream.xml @@ -544,6 +544,7 @@ If a stream is closed or you pass an invalid argument, exceptions are thrown imm + The buffer to write data from. The buffer to write data from. From 4400c334bf11e366a57d5bf0f74b07d34c972163 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 19 Mar 2024 16:11:46 -0700 Subject: [PATCH 12/12] remove examples from rijndael --- xml/System.Security.Cryptography/Rijndael.xml | 76 +++++++------------ 1 file changed, 27 insertions(+), 49 deletions(-) diff --git a/xml/System.Security.Cryptography/Rijndael.xml b/xml/System.Security.Cryptography/Rijndael.xml index 18ca984d766..fe7b78f778a 100644 --- a/xml/System.Security.Cryptography/Rijndael.xml +++ b/xml/System.Security.Cryptography/Rijndael.xml @@ -74,19 +74,13 @@ Represents the base class from which all implementations of the symmetric encryption algorithm must inherit. - -compatible). > [!IMPORTANT] -> The class is the predecessor of the algorithm. You should use the algorithm instead of . For more information, see the entry [The Differences Between Rijndael and AES](https://docs.microsoft.com/archive/blogs/shawnfa/the-differences-between-rijndael-and-aes) in the .NET Security blog. - -## Examples - The following code example uses the class to encrypt and then decrypt data. - - :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/fileexample.cs" interactive="try-dotnet" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb" id="Snippet1"::: +> The class is the predecessor of the algorithm. You should use the algorithm instead of . For more information, see the entry [The Differences Between Rijndael and AES](https://docs.microsoft.com/archive/blogs/shawnfa/the-differences-between-rijndael-and-aes) in the .NET Security blog. ]]> @@ -134,27 +128,19 @@ Initializes a new instance of . - to the default values listed in the following table. - -|Field|Default Value| -|-----------|-------------------| -||256| -||128| -||128| - - - -## Examples - The following code example uses the class to encrypt and then decrypt data. - - :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/fileexample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb" id="Snippet1"::: - + to the default values listed in the following table. + +|Field|Default Value| +|-----------|-------------------| +||256| +||128| +||128| + ]]> Cryptographic Services @@ -222,19 +208,11 @@ Creates a cryptographic object to perform the algorithm. A cryptographic object. - is . - - - -## Examples - The following code example uses the class to encrypt and then decrypt data. - - :::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography/CryptoStream/Overview/fileexample.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/cryptography.rijndael.create.file/vb/fileexample.vb" id="Snippet1"::: - + is . + ]]> The algorithm was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible. @@ -301,11 +279,11 @@ Creates a cryptographic object to perform the specified implementation of the algorithm. A cryptographic object. - The algorithm described by the parameter was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible.