user34537
user34537

Reputation:

Get/open temp file in .NET

I would like to do something like the below. What function returns me an unique file that is opened? so i can ensure it is mine and i wont overwrite anything or write a complex fn generate/loop

BinaryWriter w = GetTempFile(out fn);
w.close();
File.Move(fn, newFn);

Upvotes: 12

Views: 7745

Answers (4)

ScottS
ScottS

Reputation: 8553

Another alternative is the TempFileCollection class. It provides an IDisposable wrapper much like what is suggested in the docs for Path.GetTempFileName().

Upvotes: 3

Jeffrey Hantin
Jeffrey Hantin

Reputation: 36534

You can do something like this:

var path = Path.GetTempFileName();
var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
var writer = new BinaryWriter(stream);
  ...

Upvotes: 2

Pat
Pat

Reputation: 5282

Can use the GetTempFileName() method to obtain a fairly unique temporary file name.

Upvotes: 1

Joey
Joey

Reputation: 354864

There are two methods for this:

Usually the first method suffices; the documentation for GetRandomFileName says:

When the security of your file system is paramount, this method should be used instead of GetTempFileName.

Upvotes: 19

Related Questions