How to convert Stream to ByteArray in C# and VB.NET

To convert Stream to ByteArray in C# and VB.NET you can use the following snippet.

Samples

Sample C#

Sample VB.NET

Compatibility: working .NET 2.0 working .NET 3.0 not tested .NET 3.5 not working .NET 4.0 not working .NET 4.5not working .NET 4.6

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

How to read a file into a bytearray in Java

To read a file into a bytearray in Java you can use the following snippet.

Sample Java

public static byte[] ReadFileIntoByteArray(File fileName) throws IOException {
    InputStream inputStream = new FileInputStream(fileName);
    byte[] bytes;
        
    try {
        long fileLength = fileName.length();
        if (fileLength > Integer.MAX_VALUE) {
            bytes = new byte[(int)fileLength];
			int readOffset = 0;
			int readCount = 0;
			while ((readCount=inputStream.read(bytes, readOffset, bytes.length-readOffset)) >= 0 && readOffset < bytes.length ) {
				readOffset += readCount;
			}
			if (bytes.length > readOffset) {
				throw new IOException("Could not completely read file " + fileName.getName());
			}
        }
		else{
			throw new IOException("File " + fileName.getName() + " too large (>2GB)!");
		}
    }
    finally {
        inputStream.close();
    }
    return bytes;
}

How to read a file into a bytearray in C# and VB.NET

To read a file into a bytearray in C# and VB.NET you can use the following snippet.

Sample C#

var bytes = System.IO.File.ReadAllBytes(fileName);

Sample VB.NET

Dim bytes = System.IO.File.ReadAllBytes(fileName)