Creating a Random File in C#

前端 未结 5 1919
执念已碎
执念已碎 2020-12-14 07:29

I am creating a file of a specified size - I don\'t care what data is in it, although random would be nice. Currently I am doing this:

        var sizeInMB          


        
5条回答
  •  暖寄归人
    2020-12-14 08:17

    There's no faster way then taking advantage of the sparse file support built into NTFS, the file system for Windows used on hard disks. This code create a one gigabyte file in a fraction of a second:

    using System;
    using System.IO;
    
    class Program {
        static void Main(string[] args) {
            using (var fs = new FileStream(@"c:\temp\onegigabyte.bin", FileMode.Create, FileAccess.Write, FileShare.None)) {
                fs.SetLength(1024 * 1024 * 1024);
            }
        }
    }
    

    When read, the file contains only zeros.

提交回复
热议问题