I maintain a library called PGPCore for using PGP encryption in C#, in order to test how this performs when processing large files I needed to create a large file full of random data to check it was encrypting/decrypting as expected. After a bit of searching the answers to this Stack Overflow pointed me in the right direction.

The easiest way to create a large file is to just set the length of a FileStream.

using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
{
    fileStream.SetLength(sizeInMB * 1024 * 1024);
}

The problem with this method is that the file is just filled with 0’s so it is not a good test of encryption or compression.

If you want to create a file of a specified size filled with random data then the below function does the job.

private void CreateRandomFile(string filePath, int sizeInMb)
{
	// Note: block size must be a factor of 1MB to avoid rounding errors
	const int blockSize = 1024 * 8;
	const int blocksPerMb = (1024 * 1024) / blockSize;

	byte[] data = new byte[blockSize];

	using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
	{
		using (FileStream stream = File.OpenWrite(filePath))
		{
			for (int i = 0; i < sizeInMb * blocksPerMb; i++)
			{
				crypto.GetBytes(data);
				stream.Write(data, 0, data.Length);
			}
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *