Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建具有特定大小的新文件_C#_.net - Fatal编程技术网

C# 创建具有特定大小的新文件

C# 创建具有特定大小的新文件,c#,.net,C#,.net,我需要创建包含随机数据但具有特定大小的文件。我想不出一个有效的方法来做这件事 目前,我正在尝试使用BinaryWriter将空字符数组写入文件,但在尝试将数组创建为特定大小时出现内存不足异常 char[] charArray = new char[oFileInfo.FileSize]; using (BinaryWriter b = new BinaryWriter(File.Open(strCombined, FileMode.Create), System.Text.Encoding.U

我需要创建包含随机数据但具有特定大小的文件。我想不出一个有效的方法来做这件事

目前,我正在尝试使用BinaryWriter将空字符数组写入文件,但在尝试将数组创建为特定大小时出现内存不足异常

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

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


谢谢。

看起来您的文件太大了。 它适用于较小的文件大小吗


如果是,您应该使用缓冲区(char[]只有大约100字节,您将循环直到达到所需大小)

这将创建一个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);
}

我实际上需要使用这个:

oFileInfo
是我要创建的文件的自定义文件信息对象
FileSize
是它作为
int
的大小


谢谢。

这取决于leinfo.FileSize的
大小;不管怎样,它看起来很好…我想你的问题已经在这里得到了回答:Markus-是的,这回答了我的问题,FileStream.SetLength就是我所需要的!非常感谢。那么随机数据位呢?
using (var fs = new FileStream(strCombined, FileMode.Create, FileAccess.Write, FileShare.None))
{
    fs.SetLength(oFileInfo.FileSize);
}