I want to create a byte array against the given size filled with random data.How can I do that?Signature of my method would be like this:
private byte[] GetByteArray(int sizeInKb)
{
}
This is what I have tried:
private byte[] GetByteArray(int sizeInKb)
{
var rnd = new Random();
var bytes = new Byte[sizeInKb*1024];
rnd.NextBytes(bytes);
return bytes;
}
Here I want to return byte array conataining random data against value of sizeInKb. Is my array size correct , when user inputs value in kb e.g. 10 KB.
Try the Random.NextBytes method https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes?view=netframework-4.7.2
private byte[] GetByteArray(int sizeInKb)
{
Random rnd = new Random();
byte[] b = new byte[sizeInKb * 1024]; // convert kb to byte
rnd.NextBytes(b);
return b;
}
If you need cryptographically safe random bytes, use System.Security.Cryptography.RNGCryptoServiceProvider instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With