9.15 Create a Temporary File


Problem

You need to create a file that will be placed in the user -specific temporary directory and will have a unique name so that it won't collide with temporary files generated by other programs.

Solution

Use the static GetTempFileName method of the System.IO. Path class, which returns a path made up of the user's temporary directory and a randomly generated file name.

Discussion

There are a number of approaches to generating temporary files. In simple cases, you might just create a file in the application directory, possibly using a GUID or a timestamp in conjunction with a random value as the file name. However, the Path class provides a helper method that can save you some work. It creates a file with a unique file name in the current user's temporary directory. This might be a path like c:\documents and settings\username\local settings\temp\tmpac9.tmp.

 using System; using System.IO; public class TemporaryFile {     private static void Main() {         string tempFile = Path.GetTempFileName();         Console.WriteLine("Using " + tempFile);         FileStream fs = new FileStream(tempFile, FileMode.Open);         // (Write some data.)         fs.Close();         // Now delete the file.         File.Delete(tempFile);         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net