0
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);
                }
            }
        }
    }
}

The problem is i want to generate text files types and with random content and also random size for example files size can be 6byte or 60kb or 7mb even 1gb any range of sizes.

For example the method instead getting sizeInMb it will get filePath and the number of files will generate the files sizes content and names automatic.

public static void GenerateFiles(string filePath, int numOfFiles)

if the numOfFiles is 10 then it will generate also random number of files between 1 to 10 and if numOfFiles is 500 then random number of files between 1 and 500.

Eliot Shein
  • 197
  • 1
  • 9
  • Check out the [`Random`](https://learn.microsoft.com/en-us/dotnet/api/system.random?view=net-6.0) class – MindSwipe Jun 02 '22 at 09:53

1 Answers1

0

I pulled this from Faster way to generate random text file C# and remember using it for a school project in windows forms so I don't know if it's outdated.

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);
    }
}

As for generating multiple text files you could just wrap the whole function around a for loop, and have its variable dictate the file name.

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

   // File editing
}

I hope this helps!

hrodric
  • 390
  • 2
  • 12