views:

134

answers:

3

I've written some code to generate a sequence of random characters, but it does not:

        byte[] sbytes = { 1, 0, 1, 0, 1 };
        String sstring;
        System.Random r = new System.Random();

        r.NextBytes(sbytes);
        sstring = Convert.ToBase64String(sbytes);

        sstring = Path.GetRandomFileName();

        sstring = sstring.Replace("=", "");
        sstring = sstring.Replace(".", "");

        textBox1.Text = sstring.ToString();

I believe the problem is between NextBytes and ToBase64String. I don't know how to make this work. How do you do the correct conversion to pass it to a textbox for display?

A: 

You're replacing the random data with the filename:

sstring = Convert.ToBase64String(sbytes);
sstring = Path.GetRandomFileName();

The second statement ignores the existing value set by the first statement, so the calls to NextRandom() and ToBase64String are completely irrelevant.

What exactly are you trying to do?

EDIT: This isn't really a very good way of creating a random password. For one thing you should use SecureRandom rather than Random, and you might also want to avoid confusing features such as "0" and "O", and "l" and "1" looking the same. You could just use Path.GetRandomFileName on its own, but it's not really what it's designed for.

Jon Skeet
Just make a random password using ToBase64String and GetRandomFilename.
Nightforce2
What did you mean by confusing O and 0 There is no alphabet used in the sample string in the first place...
Nightforce2
@Nightforce2: What "sample string" are you talking about? If you use base64 from random data you can *absolutely* get a string like OOO0O0OO which in many fonts will be very hard to distinguish.
Jon Skeet
Thought you where talking about the byte string. I Gotcha now!
Nightforce2
+4  A: 

If you want to generate a random password here's a great example. And here's another one which is more naive. Simply forget about the Path.GetRandomFileName function.

Darin Dimitrov
+1 for persistence!
Mark Byers
Thanks a lot guys. Really appreciate your help.
Nightforce2
A: 

if you wrote

sstring += Path.GetRandomFileName();

I'm guessing the result would be more like what you are looking for however it's only pseudo random and you should take a look at the link Darin posted

Rune FS