【问题标题】:How To Create A TempFile rapidly in C#?如何在 C# 中快速创建临时文件?
【发布时间】:2011-06-15 03:49:39
【问题描述】:

我想快速创建一个指定大小的临时文件,内容并不重要,我只是希望操作系统给文件足够的空间,以便其他文件无法保存在磁盘中。 我知道一件事叫做“SparseFile”,但我不知道如何创建一个。 谢谢。

【问题讨论】:

    标签: c# .net file


    【解决方案1】:

    喜欢 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() );
        }
    }
    

    这是一个运行示例,显示了此操作的执行速度:

    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 将数据写入文件,需要很多时间
    • 不,它没有。我已经更新了帖子以提供时间示例。
    【解决方案2】:

    看看这个:NTFS Sparse Files with C#

    【讨论】:

    • @wbpmrck - 看,如果您期望得到好的答案,请提供更多详细信息。你希望我和其他人猜你有什么系统吗?您意识到并非所有文件系统都支持稀疏文件,对吧?
    【解决方案3】:

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

    查看this question 的答案以快速创建大文件(最好的方法与holtavolt 建议使用FileStream.SetLength 相同)。

    【讨论】:

    • 确实如此。您可以轻松地在 20 GB 硬盘上创建十几个“空”的 10 GB 稀疏文件——这将搞砸每个磁盘使用分析工具的统计数据。
    猜你喜欢
    • 2013-05-22
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多