使用随机数使文件名唯一可以安全吗? [英] Safe to use random numbers to make filenames unique?

查看:97
本文介绍了使用随机数使文件名唯一可以安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个基本上处理数据并输出许多文件的程序.每次使用都无法产生10-20个以上的文件.我只是想知道使用此方法生成唯一文件名是否是一个好主意? rand是否有可能选择,假设x,然后在10个实例内再次选择x.使用random();是个好主意吗?任何输入将不胜感激!

I'm writing a program which basically processes data and outputs many files. There is no way it will be producing more than 10-20 files each use. I just wanted to know if using this method to generate unique filenames is a good idea? is it possible that rand will choose, lets say x and then within 10 instances, choose x again. Is using random(); a good idea? Any inputs will be appreciated!

Random rand = new Random ();
int randNo = rand.Next(100000,999999)l

using (var write = new StreamWriter("C:\\test" + randNo + ".txt") 
{
// Stuff
}

推荐答案

我只是想知道使用这种方法生成唯一文件名是否是个好主意?

I just wanted to know if using this method to generate unique filenames is a good idea?

不.唯一性不是随机性的属性.随机表示结果值不以任何方式取决于先前的状态.这意味着有可能重复.您可以连续连续多次获得相同的数字(尽管不太可能).

No. Uniqueness isn't a property of randomness. Random means that the resulting value is not in any way dependent upon previous state. Which means repeats are possible. You could get the same number many times in a row (though it's unlikely).

如果您想要唯一的值,请使用GUID:

If you want values which are unique, use a GUID:

Guid.NewGuid();


如以下评论中所指出的那样,该解决方案不是 perfect .但我认为这足以解决当前的问题.这个想法是Random设计为随机的,而Guid设计为唯一的.从数学上讲,随机"和唯一"是要解决的重要问题.


As pointed out in the comments below, this solution isn't perfect. But I contend that it's good enough for the problem at hand. The idea is that Random is designed to be random, and Guid is designed to be unique. Mathematically, "random" and "unique" are non-trivial problems to solve.

都不是100%完美.但关键是要针对预期的功能简单地使用两者中的正确一项.

Neither of these implementations is 100% perfect at what it does. But the point is to simply use the correct one of the two for the intended functionality.

或者,举个比喻...如果您想将钉子钉在一块木头上,是否100%保证了钉子可以成功完成此操作?不会.锤子接触钉子时会破碎的可能性不为零.但是我仍然会伸手拿锤子,而不是陪审团用螺丝刀操纵东西.

Or, to use an analogy... If you want to hammer a nail into a piece of wood, is it 100% guaranteed that the hammer will succeed in doing that? No. There exists a non-zero chance that the hammer will shatter upon contacting the nail. But I'd still reach for the hammer rather than jury rigging something with the screwdriver.

这篇关于使用随机数使文件名唯一可以安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆