-1

Program to populate a text file in C#

I am trying to use make a function using random to generate random strings and add them to the file. But it keeps repeating the same string over and over.

Need ideas on how to do that.

string va = "2346789ABCDEFGHJKLMNPQRTUVWXYZabcdefghjkmnpqrtuvwxyz";
        Random ran = new Random();
        string[] txt = new string[] {};
        
        for (int i = 0; i < 25; i++)
        {
            while (txt.Length < 8)
            {
                txt[i]= va[0 .. ran.Next()];
            }
        }
        for (int i = 0; i < txt.Length; i++) {
            File.AppendAllText($"Externalfiles/{Exfile}", txt[I]);

I am looking for a function that uses only string and random. And gives multiple random strings.

my program has the need for an iterative loop which in itself gives a new string for every iteration so that I can add those strings directly to the file.

Other Methods are also appreciated. :))

  • I suppose the while should be `while (txt[i].Length < 8)` (but watch out, it starts out as `null`, so first initialize to empty string). Also you probably want to *add* to that text: `txt[i] += va...` – Hans Kesting Jan 21 '22 at 12:48
  • 1
    Does this answer your question? [How can I generate random alphanumeric strings?](https://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings) – Bill Tür stands with Ukraine Jan 21 '22 at 12:54
  • "I am trying to use make a function using random", plus, "But it keeps repeating the same string over and over." --> Move your Random instance OUT of the Function and into the Class. See the answer by tuncaycemuzun below. The problem is if you call the function in rapid succession then it will use the same time based seed on subsequent calls and give you the same "random" character. Moving your Random instance out to class level and re-using it eliminates this problem. – Idle_Mind Jan 21 '22 at 13:19

2 Answers2

1

Using the UniqueRandom class, you can create a range of numbers with the length of your string, and any string characters whose index is generated will be removed from the UniqueRandom class.

class UniqueRandom
{
    private readonly List<int> _currentList;
    private readonly Random _random = new Random();

    public UniqueRandom(IEnumerable<int> seed)
    {
       _currentList = new List<int>(seed);
    }

    public int Next()
    {
       if (_currentList.Count == 0)
       {
          throw new ApplicationException("No more numbers");
       }

       int i = _random.Next(_currentList.Count);
       int result = _currentList[i];
       _currentList.RemoveAt(i);
       return result;
    }
    public bool IsEmpty
    {
       get
       {
          return _currentList.Count == 0;
       }
    }
}

Now use

string va = "2346789ABCDEFGHJKLMNPQRTUVWXYZabcdefghjkmnpqrtuvwxyz";
UniqueRandom u = new UniqueRandom(Enumerable.Range(0, va.Length - 1));

while (!u.IsEmpty)
{
    string txt = string.Empty;
    while(txt.Length < 8)
    {
        if (u.IsEmpty)
          break;
        int select = u.Next();
        txt += va[select];
    }
    File.AppendAllText($"Externalfiles/{Exfile}", txt);
}
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17
  • You're calling `CreateRandomText()` from within a LOOP. Since your function creates an instance of Random in it, you'll get repeated characters since it uses time as the seed. Move Random out to CLASS level. – Idle_Mind Jan 21 '22 at 13:21
  • I did not notice that duplicate characters should not be present in words. I edited the answer – Meysam Asadi Jan 21 '22 at 13:54
  • 1
    Most likely there was enough of a delay in the loop since it was writing to a file. The old version could have failed if used differently. New version looks way better! – Idle_Mind Jan 21 '22 at 14:12
0

You can use the following function to create a Random String.

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

How can I generate random alphanumeric strings?