How to create a temporary file (for writing to) in C#? [duplicate]

為{幸葍}努か 提交于 2019-12-01 15:06:37

I've also had the same requirement before, and I've created a small class to solve it:

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;
  }
}

It creates a temporary file in a folder you specify or in the system temporary folder. It's a disposable class, so at the end of its life (either Dispose or the destructor), it deletes the file. You get the name of the file created (and path) through the FilePath property. You can certainly extend it to also open the file for writing and return its associated FileStream.

An example usage:

using (var tempFile = new TemporaryFile()) {
    // use the file through tempFile.FilePath...
}
Will

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"))

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!