创建一个临时文件名我也有同样的要求之前,我已经创建了一个小班解决它:
public sealed class TemporaryFile : IDisposable {
public TemporaryFile() :
this(Path.GetTempPath()) { }
public TemporaryFile(string directory) {
Create(Path.Combine(directory, Path.GetRandomFileName()));
}
~TemporaryFile() {
Delete();
}
public void Dispose() {
Delete();
GC.SuppressFinalize(this);
}
public string FilePath { get; private set; }
private void Create(string path) {
FilePath = path;
using (File.Create(FilePath)) { };
}
private void Delete() {
if (FilePath == null) return;
File.Delete(FilePath);
FilePath = null;
}
}
它在您指定的文件夹或系统临时文件夹中创建一个临时文件。它是一次性类,所以在其生命结束时(Dispose
或析构函数),它会删除文件。您将获得通过FilePath
属性创建的文件的名称(和路径)。您当然可以扩展它来打开文件进行写入并返回其相关的FileStream
。
使用示例:
using (var tempFile = new TemporaryFile()) {
// use the file through tempFile.FilePath...
}
我还没有看到Path.GetTempDirectory,是不是System.IO.GetTempPath? – Biri 2008-08-21 14:54:21