Preallocating file space in C#?

后端 未结 3 514
清酒与你
清酒与你 2021-02-05 08:40

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 lar

相关标签:
3条回答
  • 2021-02-05 09:18

    FileStream.SetLength is the one you want. The syntax:

    public override void SetLength(
        long value
    )
    
    0 讨论(0)
  • 2021-02-05 09:36

    Unfortunately, you can't really do this just by seeking to the end. That will set the file length to something huge, but may not actually allocate disk blocks for storage. So when you go to write the file, it will still fail.

    0 讨论(0)
  • 2021-02-05 09:42

    If you have to create the file, I think that you can probably do something like this:

    using (FileStream outFile = System.IO.File.Create(filename))
    {
        outFile.Seek(<length_to_write>-1, SeekOrigin.Begin);
        OutFile.WriteByte(0);
    }
    

    Where length_to_write would be the size in bytes of the file to write. I'm not sure that I have the C# syntax correct (not on a computer to test), but I've done similar things in C++ in the past and it's worked.

    0 讨论(0)
提交回复
热议问题