Creating a Random File in C#

前端 未结 5 1914
执念已碎
执念已碎 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:15

    The efficient way to create a large file:

        FileStream fs = new FileStream(@"C:\temp\out.dat", FileMode.Create);
        fs.Seek(1024 * 6, SeekOrigin.Begin);
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        fs.Write(encoding.GetBytes("test"), 0, 4);
        fs.Close();
    

    However this file will be empty (except for the "test" at the end). Not clear what is it exactly you are trying to do -- large file with data, or just large file. You can modify this to sparsely write some data in the file too, but without filling it up completely. If you do want the entire file filled with random data, then the only way I can think of is using Random bytes from Jon above.

提交回复
热议问题