Home >Backend Development >C++ >How to Efficiently Convert a Stream to a Byte Array in .NET?
The transforming input to byte array is a common task in programming. There are many ways to achieve this purpose. The best way depends on specific use cases and available resources.
Use binaryReader
In .NET 3.5, a commonly used method was to use the BinaryReader class, as shown in the code fragment below:
This method allocates an array of specified length and reads all the contents of the flow into the array. However, it depends on the accurate understanding of the flow length, and this is not always available.
<code class="language-csharp">Stream s; byte[] b; using (BinaryReader br = new BinaryReader(s)) { b = br.ReadBytes((int)s.Length); }</code>Read and write in blocks
If the length of the flow is unreliable or unreliable, the use of circular segments to read flow may be more efficient:
This method repeatedly reads the data into the buffer until the end of the current. It accumulates data into MemoryStream before returning the byte array.Or, in the .NET 4 and higher versions, you can use stream.copyto to achieve the same results as the above cycle:
<code class="language-csharp">public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } }</code>
Other precautions
<code class="language-csharp">using (MemoryStream ms = new MemoryStream()) { s.CopyTo(ms); return ms.ToArray(); }</code>The choice of these methods depends on several factors:
The reliability of the flow length:
If it is known and reliable, the use of binaryReader can improve efficiency.Stream:
The above is the detailed content of How to Efficiently Convert a Stream to a Byte Array in .NET?. For more information, please follow other related articles on the PHP Chinese website!