How to generate string of a certain length to insert into a file to meet a file size criteria?

C#String.NetOperations

C# Problem Overview


I have a requirement to test some load issues with regards to file size. I have a windows application written in C# which will automatically generate the files. I know the size of each file, ex. 100KB, and how many files to generate. What I need help with is how to generate a string less than or equal to the required file size.

pseudo code:

long fileSizeInKB = (1024 * 100); //100KB
int numberOfFiles = 5;

for(var i = 0; i < numberOfFiles - 1; i++) {
     var dataSize = fileSizeInKB;
     var buffer = new byte[dataSize];
     using (var fs = new FileStream(File, FileMode.Create, FileAccess.Write)) {

     }
}

C# Solutions


Solution 1 - C#

You can always use the a constructor for string which takes a char and a number of times you want that character repeated:

string myString = new string('*', 5000);

This gives you a string of 5000 stars - tweak to your needs.

Solution 2 - C#

Easiest way would be following code:

var content = new string('A', fileSizeInKB);

Now you've got a string with as many A as required.

To fill it with Lorem Ipsum or some other repeating string build something like the following pseudocode:

string contentString = "Lorem Ipsum...";
for (int i = 0; i < fileSizeInKB / contentString.Length; i++)
  //write contentString to file

if (fileSizeInKB % contentString.Length > 0)
  // write remaining substring of contentString to file

Edit: If you're saving in Unicode you may need to half the filesize count because unicode uses two bytes per character if I remember correctly.

Solution 3 - C#

There are so many variations on how you can do this. One would be, fill the file with a bunch of chars. You need 100KB? No problem.. 100 * 1024 * 8 = 819200 bits. A single char is 16 bits. 819200 / 16 = 51200. You need to stick 51,200 chars into a file. But consider that a file may have additional header/meta data, so you may need to account for that and decrease the number of chars to write to file.

Solution 4 - C#

As a partial answer to your question I recently created a portable WPF app that easily creates 'junk' files of almost any size: https://github.com/webmooch/FileCreator

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVajNyiajView Question on Stackoverflow
Solution 1 - C#marc_sView Answer on Stackoverflow
Solution 2 - C#Florian von SpiczakView Answer on Stackoverflow
Solution 3 - C#KonView Answer on Stackoverflow
Solution 4 - C#BoscoView Answer on Stackoverflow