创建具有特定大小的新文件
我需要创建包含随机数据但具有特定大小的文件。 我无法找到一种有效的方法。
目前我正在尝试使用BinaryWriter将空char数组写入文件但是在尝试将数组创建为特定大小时出现Out of Memory Exception
char[] charArray = new char[oFileInfo.FileSize]; using (BinaryWriter b = new BinaryWriter(File.Open(strCombined, FileMode.Create), System.Text.Encoding.Unicode)) { b.Write(charArray); }
建议?
谢谢。
我实际上需要使用它:
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
是我想要创建的文件的自定义文件信息对象。 FileSize
的大小为int
。
谢谢。
这将创建一个100字节的文件
System.IO.File.WriteAllBytes("file.txt", new byte[100]);
不知怎的,我错过了关于所需随机数据的部分。 在随机数据形成的地方展开,您可以执行以下操作:
//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); }
看起来你的FileSize非常大。 它是否适用于较小的文件大小?
如果是,你应该使用一个缓冲区(char []只是大约100字节,你循环,直到达到所需的大小)