3

I want to Create a tempFile with specified Size very quickly,and the content is not important,i just want the OS give the file enough space so that other file cannot save in the disk. And i know one thing called "SparseFile" but i don't know how to create one. thanks.

Alex Aza
  • 76,499
  • 26
  • 155
  • 134
wbpmrck
  • 31
  • 1

3 Answers3

4

Like FileStream.SetLength?

http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx

using System;
using System.IO;
using System.Text;

class Test
{

    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Delete the file if it exists.
        if (File.Exists(path))
        {
            File.Delete(path);
        }

        //Create the file.
        DateTime start = DateTime.Now;
        using (FileStream fs = File.Create(path))
        {
            fs.SetLength(1024*1024*1024);
        }
        TimeSpan elapsed = DateTime.Now - start;
        Console.WriteLine(@"FileStream SetLength took: {0} to complete", elapsed.ToString() );
    }
}

Here's a sample run, showing how quickly this operation executes:

C:\temp>dir
 Volume in drive C has no label.
 Volume Serial Number is 7448-F891

 Directory of C:\temp

06/17/2011  08:09 AM    <DIR>          .
06/17/2011  08:09 AM    <DIR>          ..
06/17/2011  08:07 AM             5,120 ConsoleApplication1.exe
               1 File(s)          5,120 bytes
               2 Dir(s)  142,110,666,752 bytes free

C:\temp>ConsoleApplication1.exe
FileStream SetLength took: 00:00:00.0060006 to complete

C:\temp>dir
 Volume in drive C has no label.
 Volume Serial Number is 7448-F891

 Directory of C:\temp

06/17/2011  08:09 AM    <DIR>          .
06/17/2011  08:09 AM    <DIR>          ..
06/17/2011  08:07 AM             5,120 ConsoleApplication1.exe
06/17/2011  08:09 AM     1,073,741,824 MyTest.txt
               2 File(s)  1,073,746,944 bytes
               2 Dir(s)  141,033,644,032 bytes free
holtavolt
  • 4,378
  • 1
  • 26
  • 40
3

Take a look at this: NTFS Sparse Files with C#

Alex Aza
  • 76,499
  • 26
  • 155
  • 134
  • 3
    @wbpmrck - look, if you expect good answer, please provide more details. Do you expect me and others guess what system you have? You realize that not all the file systems support sparse files, right? – Alex Aza Jun 15 '11 at 05:24
1

Sparse files might not be what you want here, the zeroed holes in sparse files won't actually be allocated on disk and so won't prevent the drive from filling up with other data.

See the answers to this question for a quick way to create a large file (the best of which is the same as holtavolt's suggestion to use FileStream.SetLength).

Community
  • 1
  • 1
Jeffy
  • 795
  • 5
  • 11
  • Indeed. You can easily create a dozen of 'empty' 10 GB sparse files on a 20 GB HDD -- which will f*ck up the statistics of every disk usage analyzing tool. – springy76 Sep 21 '11 at 21:35