473,382 Members | 1,093 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

C# random alphanumeric strings ?

Anyone got an example ?
Jul 2 '07 #1
15 52532
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
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
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
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
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
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
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
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.