[C#] 如何產生Random string

若在concurrency中, 有時須要產生一堆random number去做, 但工作上, 要制做一條unique path, 除了用primary key 外, timestamp + random number 亦是一個好選擇. 為了更精準 (或者無聊), 便嘗試了random string.

 private string RandomString(int size)
        {
            Random random = new Random((int)DateTime.Now.Ticks);
            StringBuilder builder = new StringBuilder();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            return builder.ToString();
        }

用法:

RandomString(attachmentCachePathRandomStringSize)

Reference:
http://stackoverflow.com/questions/1122483/random-string-generator-returning-same-string

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.