[code snippet] 生成随机大文件
一个无聊的测试代码,因为要测试大文件的网络传输,就写了一个随机大文件生成脚本,做个备份。
基本上都是 GPT 生成的,哈哈。
C# 代码
csharp
namespace ConsolePlayground;
internal class BigFileGenerater
{
public async Task Run()
{
Console.WriteLine("大文件生成工具,输入要生成的文件大小,单位 GB");
Console.WriteLine();
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
return;
}
if (!double.TryParse(input.Trim(), out var size))
{
return;
}
if (size <= 0 || size > 1000)
{
throw new ArgumentOutOfRangeException("size");
}
var byteSize = size * 1024 * 1024 * 1024;
var folder = Environment.CurrentDirectory;
Console.WriteLine($"将在当前目录 {folder} 生成 {size} GB 的文件");
Console.WriteLine("是否继续? Y/N");
input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
return;
}
if (input.Trim().ToUpper() != "Y")
{
return;
}
Console.WriteLine("开始生成...");
await Genetate(folder, byteSize);
Console.WriteLine("结束生成");
}
private async Task Genetate(string folder, double size)
{
var file = Path.Combine(folder, $"TEMP_{DateTime.Now:yyyyMMddHHmmss.fff}.tmp");
using var fileStream = new FileStream(file, FileMode.OpenOrCreate);
var rng = new Random();
int step = 1024 * 1024;
int count = (int)Math.Ceiling(size / step);
for (int i = 0; i < count; i++)
{
byte[] bytesToWrite = GenerateRandomBytes(rng, step);
await fileStream.WriteAsync(bytesToWrite, 0, step);
await fileStream.FlushAsync();
}
}
public static byte[] GenerateRandomBytes(Random rng, int length)
{
var randomBytes = new byte[length];
rng.NextBytes(randomBytes);
return randomBytes;
}
}