生成 1 億行 8 位數字文本(00000000 到 99999999),批處理太慢,求 C# 快速實現。
using System;
using System.IO;
using System.Text;
class Program {
static void Main() {
const string path = @"D:\target.txt";
const int total = 100_000_000;
const int bufferSize = 1024 * 1024; // 1MB 緩衝
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize, FileOptions.SequentialScan))
using (var sw = new StreamWriter(fs, Encoding.ASCII, bufferSize)) {
// 預分配 StringBuilder 減少內存分配
var sb = new StringBuilder(10);
for (int i = 0; i < total; i++) {
sb.Clear();
sb.Append(i.ToString("D8")); // 格式化為 8 位,不足前補 0
sw.WriteLine(sb.ToString());
// 定期刷新避免內存過大
if (i % 100000 == 0) sw.Flush();
}
}
Console.WriteLine("完成");
}
}
FileOptions.SequentialScan 提示順序寫入優化。i.ToString("D8") 直接格式化,避免手動補零邏輯。StringBuilder 復用減少 GC 壓力。Flush() 平衡內存與性能。預計幾分鐘完成(視磁盤速度)。