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

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

问题描述

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

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

我现在做的是

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

但是,这并不能保证我的 .csv 文件是唯一的.

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

我知道我遇到冲突的可能性非常低(特别是如果您认为我没有删除 .tmp 文件),但是这段代码对我来说并不好看.

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.

推荐答案

保证(统计上)唯一:

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

(引用维基上关于碰撞概率的文章:

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

...一个人每年被撞到的风险陨石估计是一颗机会在 170 亿 [19],这意味着概率约为 0.00000000006(6 × 10−11),相当于创造了几十万亿一年内的 UUID 并拥有一个复制.换句话说,只有在每个生成 10 亿个 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天全站免登陆