kennyzx
kennyzx

Reputation: 13003

FileStream.SetLength(long length) too slow when length is in gigabytes

I need to write a small tool to eat up a disk's free space (just leaving a few Kilo Bytes) to test some "low disk space" use cases. The code:

new FileStream(filename).SetLength(remaining free bytes - 1024); //leaving 1KB's free space 

But FileStream.SetLength(long length) is too slow if the length is in gigabytes, is just as slow as copying big HD movies to the disk. (Edit: Sorry I just realize that I experienced this only when writing to removable flashes, if write to other local drives, the speed is fast enough.)

So I wonder, is there a faster way to write blank files (that is, filled with zeros)? Code in C/C++ is also welcome. Or is there other trick that I can test the "low disk space" cases without having to write blank files?

Upvotes: 1

Views: 1658

Answers (2)

kennyzx
kennyzx

Reputation: 13003

After a google search I was directed to this SO question: Creating big file on Windows

That answers my question.

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109802

You can create large files without writing to them via the Windows API call SetFileValidData.

However, note that it will NOT fill the file with zeros (which is why it is faster). Also, READ CAREFULLY the documentation for that function, since there are security implications.

Upvotes: 4

Related Questions