在几秒钟内用 C# 创建一个巨大的虚拟文件 [英] Creating a Huge Dummy File in a Matter of Seconds in C#
问题描述
我想在几秒钟内创建一个巨大的虚拟文件,比如 1~2 GB.这是我用 C# 写的:
I want to create a huge dummy file say 1~2 GBs in matter of seconds. here is what I've written in C#:
file.writeallbytes("filename",new byte[a huge number]);
另一种指示状态的方式,如下所示:
and another way with indicating the status, was like following:
long FSS = din.TotalFreeSpace;
long segments = FSS / 10000;
long last_seg = FSS % 10000;
BinaryWriter br = new BinaryWriter(fs);
for (long i = 0; i < segments; i++)
{
br.Write(new byte[10000]);
this.label2.Text = "segments write :" + i.ToString() + "
" + "segments remain :" + ((segments-i)+1).ToString();
Application.DoEvents();
}
br.Write(new byte[last_seg]);
this.label2.Text += "
Done!";
br.Close();
其中 din 是磁盘信息对象
where din is Disk Information object
使用这两种方法,编写如此大但虚拟的文件需要大约 2 分钟或更长时间.还有其他更快的方法吗?
well with these two approach it takes something like 2 or more minutes to write such a big but dummy file. Is there any other faster way for doing so?
推荐答案
只需创建文件,寻找合适的大偏移量,然后写入单个字节:
Simply create the file, seek to a suitably large offset, and write a single byte:
FileStream fs = new FileStream(@"c: mphuge_dummy_file", FileMode.CreateNew);
fs.Seek(2048L * 1024 * 1024, SeekOrigin.Begin);
fs.WriteByte(0);
fs.Close();
这将产生一个 2GB 的文件,其内容基本上是不可预测的,这对您来说应该没问题.
This will yield a 2GB file with basically unpredictable contents, which should be fine for your purposes.
这篇关于在几秒钟内用 C# 创建一个巨大的虚拟文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!