简体   繁体   English

在写入文件之前创建文件并分配存储

[英]creating a file and allocating storage before writing to it

I have a file that gets GBs of data written to it over time (looping once it reaches the end). 我有一个文件,随着时间的推移会获得写入GB的数据(一旦到达结束就循环)。 I would like to create the file ahead of time and preset the storage so that the required storage is never taken up by other downloads during the writing to the file. 我想提前创建文件并预设存储空间,以便在写入文件期间其他下载内容永远不会占用所需的存储空间。 This is done using visual studio 2012 in C#. 这是使用C#中的visual studio 2012完成的。

I have tried: 我努力了:

 if (fileSizeRequirement or fileName is changed) //if filePath or file size is changed 
        {   
            //Open or create the file, set the file to size requirement, close the filestream               
            fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);           
            fileStream.SetLength((long)fileSizeRequirement);
            fileStream.Close();
        }

1) Is this an appropriate way to "preallocate" space for a folder? 1)这是为文件夹“预分配”空间的合适方式吗? 2) Will the SetLength require a seek to the beginning after setting the length or does the position in the folder stay at the beginning? 2)SetLength在设置长度后是否需要搜索到开头或文件夹中的位置是否保持在开头? 3) What is the correct way to achieve file preallocation of storage space? 3)实现存储空间文件预分配的正确方法是什么?

Thanks ahead of time and I appreciate any suggestions. 提前谢谢,我感谢任何建议。

Using SetLength is a common approach although I'd generally use a using statement here. 使用SetLength是一种常见的方法,虽然我通常在这里使用using语句。

using(var fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    fileStream.SetLength((long)fileSizeRequirement);
}

Calling fileStream.Position straight after SetLength yields 0 so you shouldn't need to seek to the beginning. SetLength产生0之后直接调用fileStream.Position ,因此您不需要寻找开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM