Create new file with specific size
Asked Answered
S

3

25

I need to create files that contain random data but are of a specific size. I cannot figure out a efficient way of doing this.

Currently I am trying to use the BinaryWriter to write an empty char array to a file but I get an Out of Memory Exception when trying to create the array to the specific size

char[] charArray = new char[oFileInfo.FileSize];

using (BinaryWriter b = new BinaryWriter(File.Open(strCombined, FileMode.Create), System.Text.Encoding.Unicode))
{
    b.Write(charArray);
}

Suggestions?

Thanks.

Selfstarter answered 7/12, 2011 at 13:53 Comment(4)
It depends on how is big oFileInfo.FileSize; anyway it seems good...Crazed
I think your question has been answered here: https://mcmap.net/q/538665/-preallocating-file-space-in-cExpressive
Markus - Yep that answers my question, FileStream.SetLength is all I need! Thank you!Selfstarter
What about the random data bit?Cirri
S
36

I actually needed to use this:

http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx

using (var fs = new FileStream(strCombined, FileMode.Create, FileAccess.Write, FileShare.None))
{
    fs.SetLength(oFileInfo.FileSize);
}

oFileInfo is a custom file info object of the file I want to create. FileSize is its size as an int.

Thanks.

Selfstarter answered 7/12, 2011 at 15:13 Comment(1)
Using System.IO.File.WriteAllBytes is a better option hereTightrope
S
12

This will create a file that is 100 bytes

System.IO.File.WriteAllBytes("file.txt", new byte[100]);

Somehow I missed the part about the random data needed. Depnding on where the random data is coming form, you could do something like the following:

//bytes to be read
var bytes = 4020;

//Create a file stream from an existing file with your random data
//Change source to whatever your needs are. Size should be larger than bytes variable
using (var stream = new FileInfo("random-data-file.txt").OpenRead())
{
    //Read specified number of bytes into byte array
    byte[] ByteArray = new byte[bytes];
    stream.Read(ByteArray, 0, bytes);

    //write bytes to your output file
    File.WriteAllBytes("output-file.txt", ByteArray);
}
Schach answered 7/12, 2011 at 13:59 Comment(0)
F
0

looks like your FileSize is very big. Does it work with a smaller file size?

if yes you should work with a buffer (the char[] is just some 100 byte and you loop until reached the desired size)

Fitzger answered 7/12, 2011 at 13:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.