2011-12-07 57 views
12

我需要創建包含隨機數據但具有特定大小的文件。我無法弄清楚這樣做的有效方法。創建特定大小的新文件

目前,我試圖用的BinaryWriter寫一個空字符數組到一個文件,但我得到一個內存溢出異常試圖創建陣列的具體尺寸

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

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

建議是什麼時候?

謝謝。

+0

什麼是oFileInfo? – Hammerstein

+0

這取決於如何大'oFileInfo.FileSize';無論如何它似乎很好... – Marco

+0

什麼是您的文件大小? – Peter

回答

0

看起來像你的FileSize非常大。 它可以使用較小的文件大小嗎?

如果是,你應該有一個緩衝的工作(炭[]只是一些100字節,你循環,直到達到所需的大小)

6

這將創建一個文件,該文件是100個字節

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

不知何故,我錯過了需要隨機數據的部分。 Depnding在其中,隨機數據即將形式,你可以這樣做以下:

//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); 
} 
相關問題