C# 如何使用 .NET 创建具有特定扩展名的临时文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/581570/
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
How can I create a temp file with a specific extension with .NET?
提问by Brann
I need to generate a unique temporary file with a .csv extension.
我需要生成一个带有 .csv 扩展名的唯一临时文件。
What I do right now is
我现在做的是
string filename = System.IO.Path.GetTempFileName().Replace(".tmp", ".csv");
However, this doesn't guarantee that my .csv file will be unique.
但是,这并不能保证我的 .csv 文件是唯一的。
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.
我知道我发生冲突的可能性非常低(特别是如果您认为我不删除 .tmp 文件),但是这段代码对我来说并不好看。
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.
当然,我可以手动生成随机文件名,直到我最终找到一个唯一的文件名(这应该不是问题),但我很想知道其他人是否找到了解决这个问题的好方法。
采纳答案by Mitch Wheat
Guaranteed to be (statistically) unique:
保证是(统计上)唯一的:
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
(To quote from the wiki article on the probabilty of a collision:
(引用维基上关于碰撞概率的文章:
...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
...一个人每年被陨石撞击的风险估计为 170 亿分之一 [19],这意味着概率约为 0.00000000006 (6 × 10?11),相当于创造几十一年中有数万亿个 UUID 并且有一个重复。换句话说,只有在接下来的 100 年中每秒生成 10 亿个 UUID 之后,仅创建一个重复项的概率约为 50%。如果地球上每个人都拥有 6 亿个 UUID,那么重复的概率约为 50%
EDIT: Please also see JaredPar's comments.
编辑:另请参阅 JaredPar 的评论。
回答by JaredPar
Try this function ...
试试这个功能...
public static string GetTempFilePathWithExtension(string extension) {
var path = Path.GetTempPath();
var fileName = Guid.NewGuid().ToString() + extension;
return Path.Combine(path, fileName);
}
It will return a full path with the extension of your choice.
它将返回带有您选择的扩展名的完整路径。
Note, it's not guaranteed to produce a unique file name since someone else could have technically already created that file. However the chances of someone guessing the next guid produced by your app and creating it is very very low. It's pretty safe to assume this will be unique.
请注意,不能保证生成唯一的文件名,因为其他人在技术上可能已经创建了该文件。然而,有人猜测您的应用程序生成的下一个 guid 并创建它的可能性非常低。可以很安全地假设这将是独一无二的。
回答by Matías
Why not checking if the file exists?
为什么不检查文件是否存在?
string fileName;
do
{
fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
} while (System.IO.File.Exists(fileName));
回答by Michael Prewecki
You can also do the following
您还可以执行以下操作
string filename = Path.ChangeExtension(Path.GetTempFileName(), ".csv");
and this also works as expected
这也按预期工作
string filename = Path.ChangeExtension(Path.GetTempPath() + Guid.NewGuid().ToString(), ".csv");
回答by Mehmet Aras
You can also alternatively use System.CodeDom.Compiler.TempFileCollection.
您也可以使用System.CodeDom.Compiler.TempFileCollection。
string tempDirectory = @"c:\temp";
TempFileCollection coll = new TempFileCollection(tempDirectory, true);
string filename = coll.AddExtension("txt", true);
File.WriteAllText(Path.Combine(tempDirectory,filename),"Hello World");
Here I used a txt extension but you can specify whatever you want. I also set the keep flag to true so that the temp file is kept around after use. Unfortunately, TempFileCollection creates one random file per extension. If you need more temp files, you can create multiple instances of TempFileCollection.
在这里,我使用了 txt 扩展名,但您可以指定任何您想要的。我还将保留标志设置为 true,以便临时文件在使用后保留。不幸的是,TempFileCollection 为每个扩展名创建一个随机文件。如果需要更多临时文件,可以创建 TempFileCollection 的多个实例。
回答by I.R.Baboon
How about:
怎么样:
Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString() + "_" + Guid.NewGuid().ToString() + ".csv")
It is highly improbable that the computer will generate the same Guid at the same instant of time. The only weakness i see here is the performance impact DateTime.Now.Ticks will add.
计算机在同一时刻生成相同的 Guid 是极不可能的。我在这里看到的唯一弱点是 DateTime.Now.Ticks 将增加的性能影响。
回答by Michael Fitzpatrick
This is what I am doing:
这就是我正在做的:
string tStamp = String.Format("{0:yyyyMMdd.HHmmss}", DateTime.Now); string ProcID = Process.GetCurrentProcess().Id.ToString(); string tmpFolder = System.IO.Path.GetTempPath(); string outFile = tmpFolder + ProcID + "_" + tStamp + ".txt";
回答by Simon
This could be handy for you... It's to create a temp. folder and return it as a string in VB.NET.
这对你来说可能很方便......它是为了创造一个临时的。文件夹并将其作为 VB.NET 中的字符串返回。
Easily convertible to C#:
轻松转换为 C#:
Public Function GetTempDirectory() As String
Dim mpath As String
Do
mpath = System.IO.Path.Combine(System.IO.Path.GetTempPath, System.IO.Path.GetRandomFileName)
Loop While System.IO.Directory.Exists(mpath) Or System.IO.File.Exists(mpath)
System.IO.Directory.CreateDirectory(mpath)
Return mpath
End Function
回答by Paolo Iommarini
This seems to work fine for me: it checks for file existance and creates the file to be sure it's a writable location. Should work fine, you can change it to return directly the FileStream (which is normally what you need for a temp file):
这对我来说似乎很好用:它检查文件是否存在并创建文件以确保它是一个可写的位置。应该可以正常工作,您可以将其更改为直接返回 FileStream(这通常是临时文件所需的):
private string GetTempFile(string fileExtension)
{
string temp = System.IO.Path.GetTempPath();
string res = string.Empty;
while (true) {
res = string.Format("{0}.{1}", Guid.NewGuid().ToString(), fileExtension);
res = System.IO.Path.Combine(temp, res);
if (!System.IO.File.Exists(res)) {
try {
System.IO.FileStream s = System.IO.File.Create(res);
s.Close();
break;
}
catch (Exception) {
}
}
}
return res;
} // GetTempFile
回答by Smita
I think you should try this:
我认为你应该试试这个:
string path = Path.GetRandomFileName();
path = Path.Combine(@"c:\temp", path);
path = Path.ChangeExtension(path, ".tmp");
File.Create(path);
It generates a unique filename and creates a file with that file name at a specified location.
它生成一个唯一的文件名并在指定位置创建一个具有该文件名的文件。