nls*_*k01 3 c# out-of-memory streamwriter large-files
我正在尝试写入然后读取一个大型随机文件来计算磁盘速度。我尝试了多种算法,但在尝试写入 1GB 文件时不断出现输出或内存异常。这是我尝试过的一些
方法一
byte[] data = new byte[8192];
Random rng = new Random();
using (FileStream stream = File.OpenWrite(filePath))
{
for (int i = 0; i < fileSizeMb * 128; i++)
{
rng.NextBytes(data);
stream.Write(data, 0, data.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
方法2
const int blockSize = 1024 * 8;
const int blocksPerMb = (1024 * 1024) / blockSize;
int count = fileSizeMb * blocksPerMb;
byte[] data = new byte[blockSize];
Random rng = new Random();
//using (FileStream stream = File.OpenWrite(filePath))
using (StreamWriter sw1 = new StreamWriter(filePath))
{
// There
for (int i = 0; i < count; i++)
{
rng.NextBytes(data);
sw1.BaseStream.Write(data, 0, data.Length);
//stream.Write(data, 0, data.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
阅读
using (StreamReader sr = new StreamReader(filePath))
{
String line = sr.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
方法一
byte[] data = new byte[8192];
Random rng = new Random();
using (FileStream stream = File.OpenWrite(filePath))
{
for (int i = 0; i < fileSizeMb * 128; i++)
{
rng.NextBytes(data);
stream.Write(data, 0, data.Length);
stream.Flush(); // BEETLE JUICE
}
}
Run Code Online (Sandbox Code Playgroud)
方法2
const int blockSize = 1024 * 8;
const int blocksPerMb = (1024 * 1024) / blockSize;
int count = fileSizeMb * blocksPerMb;
byte[] data = new byte[blockSize];
Random rng = new Random();
using (StreamWriter sw1 = new StreamWriter(filePath))
{
// There
for (int i = 0; i < count; i++)
{
rng.NextBytes(data);
sw1.BaseStream.Write(data, 0, data.Length);
sw1.baseStream.Flush(); // BEETLE JUICE
}
}
Run Code Online (Sandbox Code Playgroud)
阅读
不要将整个文件读入内存,一次只读取 4096 字节。示例代码位于http://www.csharp-examples.net/filestream-read-file/