C# 使用 .NET 生成具有给定扩展名的唯一临时文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1122928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate a unique temporary file name with a given extension using .NET
提问by Andrew Shepherd
Possible Duplicate:
How can I create a temp file with a specific extension with .net ?
It is possible to create a temporary file in .NET by calling
可以通过调用在 .NET 中创建临时文件
string fileName = System.IO.Path.GetTempFileName();
This will create a file with a .TMP extension in the temporary directory.
这将在临时目录中创建一个扩展名为 .TMP 的文件。
What if you specifically want it to have a different extension? For the sake of this example, lets say that I needed a file ending with .TR5.
如果您特别希望它具有不同的扩展名怎么办?为了这个例子,假设我需要一个以 .TR5 结尾的文件。
The obvious (and buggy) solution is to call
显而易见的(和错误的)解决方案是调用
string fileName = Path.ChangeExtension(Path.GetTempFileName(), "tr5"))
The problems here are:
这里的问题是:
- It has still generated an empty file (eg tmp93.tmp) in the temp directory, which will now hang around indefinitely
- There is no gurantee that the resulting filename (tmp93.tr5) isn't already existing
- 它仍然在临时目录中生成了一个空文件(例如 tmp93.tmp),该文件现在将无限期地挂起
- 无法保证生成的文件名 (tmp93.tr5) 不存在
Is there a straightforward and safe way to generate a temporary file with a specific file exension?
是否有一种直接且安全的方法来生成具有特定文件扩展名的临时文件?
采纳答案by Mitch Wheat
回答by Mircea Grelus
I don't know if there's a supported method for generating an extension other than .tmp, but this will give you a unique file:
我不知道是否有支持的方法来生成 .tmp 以外的扩展名,但这会给你一个独特的文件:
string fileName = Path.ChangeExtension(Path.GetTempFileName(), Guid.NewGuid().ToString() + "tr5"))
Not an elegant solution and I'm not sure if you need to then retrieve based on specific extension, but you could still write a pattern even for this.
这不是一个优雅的解决方案,我不确定您是否需要根据特定的扩展名进行检索,但您仍然可以为此编写一个模式。