Home > front end >  How to populate a text file in C#
How to populate a text file in C#

Time:01-21

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. :))

CodePudding user response:

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

CodePudding user response:

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?

  •  Tags:  
  • Related