15

Possible Duplicate:
Creating tempory folders

I'm looking for something like the tempfile module in Python: A (preferably) secure way to open a file for writing to. This should be easy to delete when I'm done too...

It seems, .NET does not have the "batteries included" features of the tempfile module, which not only creates the file, but returns the file descriptor (old school, I know...) to it along with the path. At the same time, it makes sure only the creating user can access the file and whatnot (mkstemp() I think): https://docs.python.org/library/tempfile.html


Ah, yes, I can see that. But GetTempFileName does have a drawback: There is a race condition between when the file was created (upon call to GetTempFileName a 0-Byte file gets created) and when I get to open it (after return of GetTempFileName). This might be a security issue, although not for my current application...

4

3 回答 3

26

我之前也有同样的需求,我创建了一个小类来解决它:

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...
}
于 2010-07-31T14:20:07.390 回答
8

Path.GetTempFileName and Path.GetTempPath. Then you can use this link to read/write encrypted data to the file.

Note, .NET isn't the best platform for critical security apps. You have to be well versed in how the CLR works in order to avoid some of the pitfalls that might expose your critical data to hackers.

Edit: About the race condition... You could use GetTempPath, then create a temporary filename by using

Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".TMP"))
于 2008-08-21T14:53:04.473 回答
0

I don't know of any built in (within the framework) classes to do this, but I imagine it wouldn't be too much of an issue to roll your own..

Obviously it depends on the type of data you want to write to it, and the "security" required..

This article on DevFusion may be a good place to start?

于 2008-08-21T14:52:41.887 回答