Elmex
Elmex

Reputation: 3361

Write a file temporarily on disk in C#

I have the following problem: I have some (binary) files, which are embedded in a resource. For some reasons I must write these files temporarily on disk. How should I proceeded ? Maybe this can be done with GetRandomFilename() or GetTempFileName() ?

Upvotes: 2

Views: 278

Answers (2)

codymanix
codymanix

Reputation: 29540

You can also create a Guid and make a file name from it. Guaranteed unique and fast.

GetTempFile is utterly slow because it has to scan for free file names. It just creates a prefix and adds a number to it. If a file of that name anlready exist is skips this name. This check takes time if your temp folder is full.

Is is also not possible to specify in which folder the tempfile should be created. GetTempFile always creates temp file on the windows partition. If you create large temporary files you want to specify where they should be stored.

Upvotes: 0

Colin Pickard
Colin Pickard

Reputation: 46673

GetTempFileName() is the logical one to use in this situation.

As leppie said, be sure to delete the files when you are finished to avoid any problems. GetTempFileName() will raise an IOException if it is used to create more than 65535 files without deleting previous temporary files.

Upvotes: 9

Related Questions