I am trying to create a random string of 16 characters with NO DUPLICATES. I want to say that it should not be difficult, but I am stuck.
I use 2 methods, one to generate a key and the other to remove duplicate characters. I basically created a while loop to make sure that the generated string is 16 characters long.
Something is wrong in my logic, because it just shoots at a 16-char string with duplicates. It just won't work.
Code:
public string RemoveDuplicates(string s) { string newString = string.Empty; List<char> found = new List<char>(); foreach (char c in s) { if (found.Contains(c)) continue; newString += c.ToString(); found.Add(c); } return newString; } public static string GetUniqueKey(int maxSize) { char[] chars = new char[62]; chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); byte[] data = new byte[1]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(data); data = new byte[maxSize]; crypto.GetNonZeroBytes(data); StringBuilder result = new StringBuilder(maxSize); foreach (byte b in data) { result.Append(chars[b % (chars.Length)]); } return result.ToString(); } string builder = ""; do { builder = GetUniqueKey(16); RemoveDuplicates(builder); lblDir.Text = builder; Application.DoEvents(); } while (builder.Length != 16);
source share