473,668 Members | 2,373 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# random alphanumeric strings ?

Anyone got an example ?
Jul 2 '07 #1
15 52606
bitshift wrote:
Anyone got an example ?
asdxcgfd

--
Tom Spink
University of Edinburgh
Jul 2 '07 #2
On Jul 2, 3:12 pm, "bitshift" <j...@aol.comwr ote:
Anyone got an example ?
1) Hard-code a string with all the characters you want to include
2) Use a single instance of Random (with appropriate locking if you're
going to use it from many threads)
3) Create a StringBuilder of the right length
4) In a for loop, append the next random character by using
Random.Next, passing in the string's length, and using string's
indexer
5) Call ToString on the StringBuilder

Jon

Jul 2 '07 #3
Jon Skeet [C# MVP] wrote:
On Jul 2, 3:12 pm, "bitshift" <j...@aol.comwr ote:
>Anyone got an example ?

1) Hard-code a string with all the characters you want to include
2) Use a single instance of Random (with appropriate locking if you're
going to use it from many threads)
3) Create a StringBuilder of the right length
4) In a for loop, append the next random character by using
Random.Next, passing in the string's length, and using string's
indexer
5) Call ToString on the StringBuilder

Jon
Hi Jon,

Great minds think alike.

--
Tom Spink
University of Edinburgh
Jul 2 '07 #4
bitshift wrote:
Anyone got an example ?
Also,

///
using System;
using System.Text;

....

public string GetRandomString (Random rnd, int length)
{
string charPool
= "ABCDEFGHIJKLMN OPQRSTUVWXYZabc defghijklmnopqr stuvwxyz1234567 890";
StringBuilder rs = new StringBuilder() ;

while (length-- 0)
rs.Append(charP ool[(int)(rnd.NextD ouble() * charPool.Length )]);

return rs.ToString();
}
///

Watch out for wrapping on the charPool line! Note, the method takes an
instance of the Random class, which you can instantiate with new Random().

The reason it doesn't do this itself is that (I think) the Random class uses
a timer as it's entropy source, and if you try to generate a large sequence
of random numbers quickly, the seeds will match and you'll get matching
random sequences.

So the way I tested this was:

///
public static void Main ()
{
int i = 50;
Random rnd = new Random();
while (i-- 0)
Console.WriteLi ne(GetRandomStr ing(rnd, 10));
}
///

--
Tom Spink
University of Edinburgh
Jul 2 '07 #5
Great minds think alike.

similar ones at least

Jul 2 '07 #6
Here is some code that will generate a cryptograhicall y random unique string
of any length you want:

using System.Security .Cryptography;
using System.Text;

namespace UniqueKey
{
public class KeyGenerator
{
public static string GetUniqueKey(in t maxSize)
{
char[] chars = new char[62];
chars =
"abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ1234567 890".ToCharArra y();
byte[] data = new byte[1];
RNGCryptoServic eProvider crypto = new RNGCryptoServic eProvider();
crypto.GetNonZe roBytes(data);
data = new byte[maxSize];
crypto.GetNonZe roBytes(data);
StringBuilder result = new StringBuilder(m axSize);
foreach (byte b in data)
{
result.Append(c hars[b%(chars.Length - 1)]);
}
return result.ToString ();
}
}
}

-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
BlogMetaFinder( BETA): http://www.blogmetafinder.com

"bitshift" wrote:
Anyone got an example ?
Jul 2 '07 #7
On Mon, 2 Jul 2007 09:12:40 -0500, "bitshift" <jo***@aol.comw rote:
>Anyone got an example ?
Two questions:

- do you want characters in the string to repeat or not?
- is the output going to be used for cryptographic/security purposes?

rossum

Jul 2 '07 #8
bitshift wrote:
Anyone got an example ?
private static Random rng = new Random();
public static string newPassword(int l)
{
char[] valid = { 'A', 'B', 'C', '2', '3', '4' };
StringBuilder sb = new StringBuilder(" ");
for(int i = 0; i < l; i++)
{
sb.Append(valid[rng.Next(valid. Length)]);
}
return sb.ToString();
}

Arne
Jul 3 '07 #9
Peter Bromberg [C# MVP] wrote:
char[] chars = new char[62];
chars =
"abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ1234567 890".ToCharArra y();
Why the new char[62] ?

Arne
Jul 3 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
5608
by: BGP | last post by:
I am working on a WIN32 API app using devc++4992 that will accept Dow Jones/NASDAQ/etc. stock prices as input, parse them, and do things with it. The user can just cut and paste back prices into a window and hit a button to process it. The information thus enters the program as a char array. Prices can be between $1 and $100, including cents. So we can have prices such as 3.01, 1.56, 11.57, etc. The char array is an alphanumeric...
6
4793
by: ironcito | last post by:
Hello! I'm looking for a way to have a field in my database that will automatically be filled with a random 4-character alphanumeric string every time I enter a new record. Like an autonumber field, but alphanumeric and random. Could anyone tell me how to do this? Please explain it so that a newbie can do it. Thanks a lot, and have a nice day! =)
8
3564
by: dohyohdohyoh | last post by:
I have a programming question to generate an ordered list of alphanumeric strings of length 4. two alphabets rest numberst, etc. EG 0000-9999 then A000-Z999 then AA00 to ZZ99 then AAA0 - ZZZ9 then AAAA - ZZZZ
3
5850
by: dohyohdohyoh | last post by:
I have a programming question to generate an ordered list of alphanumeric strings of length 4. two alphabets rest numberst, etc. EG 0000-9999 then A000-Z999 then AA00 to ZZ99 then AAA0 - ZZZ9 then AAAA - ZZZZ
14
4740
by: avanti | last post by:
Hi, I need to generate random alphanumeric password strings for the users in my application using Javascript. Are there any links that will have pointers on the same? Thanks, Avanti
5
8361
by: dav3 | last post by:
Howdy folks, was wondering if anyone could assist me in a better method for generating a alphanumeric sequence of 6 characters/digits. The method I am currently using gives me a random license plate number for a project I am working on. But I am unsatisfied with the results I am getting. Here is my current method, it works but like I said there has to be a better way of doing it. public static String plate() { int x = 6; char plate...
2
4724
by: franzdawg3 | last post by:
I find it hard to believe that there is not a native solution to this problem built into VB.NET but based on what I've come up with from MSDN and google if there is one it is not obvious. I have 2 situations that I need to handle through string comparison. NOTE: I am interested in comparison NOT SORTING although they seem hand in hand. The first situation is already handled and it is that if I have 3 strings "d1", "d2", and "d11",...
0
8378
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8791
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8577
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6206
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5677
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4376
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2786
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2018
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1783
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.