How to quickly create a tempfile in c #?

I want to create a tempFile with the specified size very quickly, and the content is not important, I just want the OS to give the file enough space so that another file cannot save to disk. And I know one thing called "SparseFile", but I don’t know how to create it. thank.

+3
source share
3 answers

How is 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 is an example run showing how quickly this operation is performed:

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
+4
source

Take a look at this: NTFS Permitted C # Files

+3
source

, , , .

. ( holtavolt FileStream.SetLength).

+1
source

All Articles