如何创建具有特定扩展名与.NET中的临时文件? [英] How can I create a temp file with a specific extension with .net?

查看:120
本文介绍了如何创建具有特定扩展名与.NET中的临时文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个扩展名为.csv一个唯一的临时文件。

I need to generate a unique temporary file with a .csv extension.

我现在做的

string filename = System.IO.Path.GetTempFileName().Replace(".tmp", ".csv");

然而,这并不能保证我的.csv文件将是唯一的。

However, this doesn't guarantee that my .csv file will be unique.

我知道我曾经有一个碰撞是非常低(特别是如果你认为我不删除.tmp文件)的机会,但这种code不会对我来说很好。

I know the chances I ever got a collision are very low (especially if you consider that I don't delete the .tmp files), but this code doesn't looks good to me.

当然,我可以手动生成随机文件名,直到我终于找到一个独特的一(这不应该是一个问题),但我想知道是否有其他人找到了一个很好的方式来处理这个问题。

Of course I could manually generate random file names until I eventually find a unique one (which shouldn't be a problem), but I'm curious to know if others have found a nice way to deal with this problem.

推荐答案

保证是(统计)独特的:

Guaranteed to be (statistically) unique:

string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";

(要从wiki文章引述在碰撞概率的:

(To quote from the wiki article on the probabilty of a collision:

...被撞到了一个人的年度风险   陨石估计为1   机会在17个十亿[19],这意味着   的概率是大约0.00000000006   (6×10-11),相当于赔率   创造了几十万亿   在一年和具有一个UUID的   重复。换句话说,只有在   产生1十亿的UUID每   第二个在未来100年里,   创建只是一个概率   重复将是约50%。该   一个重复的概率会   如果约50%的地球上每个人   旗下拥有6亿的UUID

...one's annual risk of being hit by a meteorite is estimated to be one chance in 17 billion [19], that means the probability is about 0.00000000006 (6 × 10−11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs

编辑:另请参阅JaredPar的意见

Please also see JaredPar's comments.

这篇关于如何创建具有特定扩展名与.NET中的临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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