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 *


Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: `POST https://dc.services.visualstudio.com/v2/track` resulted in a `400 Invalid instrumentation key` response: {"itemsReceived":1,"itemsAccepted":0,"errors":[{"index":0,"statusCode":400,"message":"Invalid instrumentation key"}]} in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack trace: #0 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response)) #2 D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\promises\src\Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\P in D:\home\site\wwwroot\wp-content\plugins\application-insights\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113