Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

11.18. Using a Temporary File in Your Application

Problem

You need a temporary file in which to store information. This file will exist only as long as the process that created it remains running.

Solution

Use the static GetTempPath and GetTempFileName methods on the Path class. To create the temporary file in the directory set as the temporary directory and get the full path to it, use the following line of code:

string tempFilePathWithFileName = Path.GetTempFileName( );

Before the application terminates, you should delete this temporary file. The following line of code deletes this file:

File.Delete(tempFilePathWithFileName);

The GetTempFileName method creates the temporary file and returns the path, including the name of the file and its extension. To create and obtain just the path without the filename, use the following line of code:

string tempFilePathWithoutFileName = Path.GetTempPath( );

Once all files are closed, before the application terminates, this temporary directory should be deleted as well. The following line of code deletes this directory and any files or subdirectories within it:

Directory.Delete(tempFilePathWithoutFileName,true);

Discussion

You should use a temporary file whenever you need to store information temporarily for later retrieval. The one thing you must remember is to delete this temporary file before the application that created it is terminated. If it is not deleted, it will remain in the user’s temporary directory until the user manually deletes it.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata