如何创建随机数量的随机内容和随机大小的文本文件?

How to create randomly number of text file with random content and random size?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GF_WPF
{
    class RandomFiles
    {
        public static void GenerateFiles(string filePath, int sizeInMb)
        {
            // Note: block size must be a factor of 1MB to avoid rounding errors
            const int blockSize = 1024 * 8;
            const int blocksPerMb = (1024 * 1024) / blockSize;

            byte[] data = new byte[blockSize];


            using (FileStream stream = File.OpenWrite(filePath))
            {
                for (int i = 0; i < sizeInMb * blocksPerMb; i++)
                {
                    stream.Write(data, 0, data.Length);
                }
            }
        }
    }
}

问题是我想生成具有随机内容和随机大小的文本文件类型,例如文件大小可以是 6 字节或 60kb 或 7mb 甚至 1gb 任何大小范围。

例如,该方法不是获取 sizeInMb,而是获取 filePath,文件数量将自动生成文件大小内容和名称。

public static void GenerateFiles(string filePath, int numOfFiles)

如果 numOfFiles 是 10,那么它也会生成 1 到 10 之间的随机文件数,如果 numOfFiles 是 500,那么它也会生成 1 到 500 之间的随机文件数。

我从 中提取了这个,并记得在 windows 表格中将它用于学校项目,所以我不知道它是否过时了。

using (var fs = File.OpenWrite(@"c:\w\test.txt"))
using (var w = new StreamWriter(fs))
{
    for (var i = 0; i < size; i++)
    {
        var text = GetRandomText(GenerateRandomNumber(1, 20));
        var number = GenerateRandomNumber(0, 5);
        var line = $"{number}. {text}";
        w.WriteLine(line);
    }
}

至于生成多个文本文件,您可以将整个函数包裹在一个 for 循环中,并让它的变量指定文件名。

for(int i = 0; i < yourLimit; i++) {
   File.CreateText($"c:\path\{i}.txt")

   // File editing
}

希望对您有所帮助!