473,509 Members | 3,075 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 52556
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.comwrote:
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.comwrote:
>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
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw xyz1234567890";
StringBuilder rs = new StringBuilder();

while (length-- 0)
rs.Append(charPool[(int)(rnd.NextDouble() * 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.WriteLine(GetRandomString(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 cryptograhically random unique string
of any length you want:

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

namespace UniqueKey
{
public class KeyGenerator
{
public static string GetUniqueKey(int maxSize)
{
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890".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 - 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.comwrote:
>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 =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890".ToCharArray();
Why the new char[62] ?

Arne
Jul 3 '07 #10
:-)
--
Milosz
"Tom Spink" wrote:
bitshift wrote:
Anyone got an example ?

asdxcgfd

--
Tom Spink
University of Edinburgh
Jul 3 '07 #11
I suppose you could do it this way if you prefer:
char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890".ToCharArray();

Actually, there are 64 characters in the string. Good catch.

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

"Arne Vajhøj" wrote:
Peter Bromberg [C# MVP] wrote:
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890".ToCharArray();

Why the new char[62] ?

Arne
Jul 3 '07 #12
whoops, my bad. There are indeed 62 characters in the string.
-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
BlogMetaFinder(BETA): http://www.blogmetafinder.com

"Arne Vajhøj" wrote:
Peter Bromberg [C# MVP] wrote:
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890".ToCharArray();

Why the new char[62] ?

Arne
Jul 3 '07 #13
On Tue, 03 Jul 2007 06:26:01 -0700, Peter Bromberg [C# MVP]
<pb*******@yahoo.yabbadabbadoo.comwrote:
I suppose you could do it this way if you prefer:
char[] chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890".ToCharArray();
I think the point is, why _wouldn't_ you prefer to do it that way?

Creating an empty 62-element array doesn't seem useful. That char[]
instance just gets thrown away when the subsequent assignment is made. So
why do it at all?

I could be missing something, but it seems to me that that line of code is
just superfluous.

Pete
Jul 3 '07 #14
Peter Bromberg [C# MVP] wrote:
"Arne Vajhøj" wrote:
>Peter Bromberg [C# MVP] wrote:
>> char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU VWXYZ1234567890".ToCharArray();
Why the new char[62] ?
whoops, my bad. There are indeed 62 characters in the string.
It does not matter. The only difference is whether 62 or
64 chars get GC'ed.

Arne
Jul 4 '07 #15

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

Similar topics

12
5589
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...
6
4782
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...
8
3551
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...
3
5839
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...
14
4712
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
8344
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...
2
4719
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...
0
7234
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7136
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...
0
7412
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...
1
7069
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...
0
7505
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
4730
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...
0
3216
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1570
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 ...
1
775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.