12

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);
asked Apr 29, 2010 at 23:07

4 Answers 4

19

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.

answered Apr 29, 2010 at 23:10
Sign up to request clarification or add additional context in comments.

Comments

3

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

answered Apr 29, 2010 at 23:48

Comments

2

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);
 ...
answered Apr 29, 2010 at 23:12

Comments

1

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

answered Apr 29, 2010 at 23:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.