How to generate text files with random content by given random size ?

Chocolade 516 Reputation points
2022-08-30T21:58:06.853+00:00
using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Security.Cryptography;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace RndFiles  
{  
    internal class GenerateRandomFiles  
    {  
		private static Random random = new Random();  
  
		public static string RandomString(int length)  
		{  
			const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
			return new string(Enumerable.Repeat(chars, length)  
				.Select(s => s[random.Next(s.Length)]).ToArray());  
		}  
	}  
}  

Using it in form1

for(int i = 0; i < 100; i++)  
            {  
                Random random = new Random();  
                File.WriteAllText(@"d:\randfiles\rand" + i + ".txt", GenerateRandomFiles.RandomString(random.Next(1,1000000)));  
            }  

The problem is that i need to give it a length : random.Next(1,1000000)

instead i want to make something like that but instead giving length to give a size for example :

random.Next(1,10) and that 1 and 10 will be MB or 1, 10 will be in GB or bytes or kb or any size to choose.
not how to make it and how it can be dome by logic.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,857 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,394 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,201 Reputation points
    2022-08-30T23:34:40.39+00:00

    Look at NuGet package Bogus

    Create a dummy class

    public class LineItem  
    {  
        public string Value { get; set; }  
        public override string ToString() => Value;  
    }  
    

    Then as a conceptual example f.Random.String2(1, 100) the max can be static or random and faker.Generate(1000) can be randomized. In the foreach, you can inspect the length of the builder and when a size is reached bail (which I didn't include) out and write to a file.

    Faker<LineItem> faker = new Faker<LineItem>()  
        .RuleFor(item => item.Value, f => f.Random.String2(1, 100));  
      
    var result = faker.Generate(1000);  
      
    StringBuilder builder = new ();  
      
    foreach (var item in result)  
    {  
        builder.Append(item);  
    }  
      
    File.WriteAllText("Dump.txt", builder.ToString());  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful