如何在C#中快速创建临时文件?

3
我想快速创建一个指定大小的临时文件,内容不重要,我只想让操作系统为该文件分配足够的空间,以防其他文件在磁盘上无法保存。 我知道有一种叫做“稀疏文件”的东西,但我不知道如何创建它。 谢谢。
3个回答

4

类似于FileStream.SetLength吗?

http://msdn.microsoft.com/zh-cn/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() );
    }
}

这里是一个示例运行,展示了此操作执行的速度之快:
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

我想在很短的时间内创建一个大文件,这种方法使用FileStream将数据写入文件中,需要很长时间。 - wbpmrck
不,它没有。我已经更新了帖子,提供了一个带有时间的示例。 - holtavolt

3

3
@wbpmrck - 看,如果你期望得到好的回答,请提供更多的细节。你希望我和其他人猜测你使用的是哪种系统吗?你意识到并不是所有的文件系统都支持稀疏文件,对吧? - Alex Aza

1

稀疏文件可能不是您想要的,稀疏文件中的零空洞实际上不会在磁盘上分配,因此不会防止驱动器被其他数据填满。

请参见此问题的答案,以快速创建大文件的方法(最好的方法与holtavolt建议使用FileStream.SetLength相同)。


确实。您可以在20 GB的硬盘驱动器上轻松创建十几个“空的”10 GB稀疏文件 - 这将破坏每个磁盘使用分析工具的统计数据。 - springy76

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接