预分配在C#中的文件空间? [英] Preallocating file space in C#?

查看:272
本文介绍了预分配在C#中的文件空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个下载应用程序,我想预先分配的硬盘的文件室之前,他们实际上是下载的,因为他们可能是相当大的,而且没有人喜欢看这个驱动器已满,请删除一些文件和再试一次。所以,从这个角度,我写了这一点。

I am creating a downloading application and I wish to preallocate room on the harddrive for the files before they are actually downloaded as they could potentially be rather large, and noone likes to see "This drive is full, please delete some files and try again." So, in that light, I wrote this.

// Quick, and very dirty
System.IO.File.WriteAllBytes(filename, new byte[f.Length]);



它的工作原理,ATLEAST直到你下载一个文件,该文件是几百MB的,或者甚至可能GB的你扔的Windows成颠簸狂热如果不能完全消灭页面文件,并完全杀死你的系统内存。哎呀。

It works, atleast until you download a file that is several hundred MB's, or potentially even GB's and you throw Windows into a thrashing frenzy if not totally wipe out the pagefile and kill your systems memory altogether. Oops.

所以,用多一点启示,我阐述了以下算法。

So, with a little more enlightenment, I set out with the following algorithm.

using (FileStream outFile = System.IO.File.Create(filename))
{
    // 4194304 = 4MB; loops from 1 block in so that we leave the loop one 
    // block short
    byte[] buff = new byte[4194304];
    for (int i = buff.Length; i < f.Length; i += buff.Length)
    {
        outFile.Write(buff, 0, buff.Length);
    }
    outFile.Write(buff, 0, f.Length % buff.Length);
}

这工作的,以及就算了,不吃亏的沉重记忆问题最后的解决方案。它仍然是缓慢的,虽然,特别是在老的硬件,因为它写出来(可能GB的价值)的数据到磁盘

This works, well even, and doesn't suffer the crippling memory problem of the last solution. It's still slow though, especially on older hardware since it writes out (potentially GB's worth of) data out to the disk.

现在的问题是:有没有更好的办法办成同样的事情?有没有告诉Windows以创建X尺寸的文件,然后直接分配文件系统上的空间,而不是实际写出的数据一吨的方式。我不在乎在所有文件中的初始化数据(我使用的协议 - BitTorrent的 - 提供哈希为发送的文件,随机未初始化的数据,因此最坏的情况是我得到的文件的机缘巧合之下和部分是正确的)。

The question is this: Is there a better way of accomplishing the same thing? Is there a way of telling Windows to create a file of x size and simply allocate the space on the filesystem rather than actually write out a tonne of data. I don't care about initialising the data in the file at all (the protocol I'm using - bittorrent - provides hashes for the files it sends, hence worst case for random uninitialised data is I get a lucky coincidence and part of the file is correct).

推荐答案

FileStream.SetLength 是你想要的。语法:

public override void SetLength(
    long value
)

这篇关于预分配在C#中的文件空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆