Managed C++: Working with Temp Files

As the owner of a software-development consulting company, I'm afforded the opportunity to work on many systems, both in terms of architecting and designing as well as coding. One thing that I see quite frequently is that many coders who are relatively new to .NET are still not taking advantage of the Path object when dealing with temporary files. Specifically, they still manually determine a unique name for the file within the application's current folder and then delete it when done.

This tip illustrates the following tasks that you can achieve with as little as one or two lines of code by using the Path class:

  • Locate the "temp" folder
  • Create a unique and optimized temporary file
  • Use and delete a temporary file

Locate the "Temp" Folder

To determine the "temp" folder, you can use the static Path::GetTempPath method. The main thing to note here is that you need to place any call to this method in a try/catch block, because a SecurityException can be thrown based on the current user's permissions:

using namespace System::Security;
using namespace System::IO;

...

String tempFolder;
try 
{
  tempFolder = Path::GetTempPath();
}
catch(SecurityException* ex)
{
  // probably means that you don't have the required permissions
}
catch(Exception* ex)
{
  // handle all other exceptions
}

Create a Unique and Optimized Temporary File

You can use the Path::GetTempFileName to retrieve the name of a unique temporary file. While not obvious from the name, this method will also create the file and return the name of the newly created file.

The file attribute is set to "Archive," which actually prevents .NET from optimizing its usage. Therefore, you can gain a small performance benefit by modifying the file's attribute so that the .NET runtime caches the file.

To do that, first construct a FileInfo object using the name of the temporary file and then set the FileInfo object's Attributes property to FileAttributes::Temporary:

using namespace System::Security;
using namespace System::IO;

...

String* fileName;
fileName->Empty;

try
{
  // Create a 0-length temporary file
  fileName = Path::GetTempFileName();

  // Set the file's attributes to "Temporary" for
  // better performance
  FileInfo* myFileInfo = new FileInfo(fileName);
  myFileInfo->Attributes = FileAttributes::Temporary;

  ...
} 
catch(Exception* ex)
{
  // handle exceptions
}

Use and Delete a Temporary File

Once you've created the temporary file, use it as you would any other file. For example, by using the code from the previous section, you could insert the following code at the bottom of the try block to write a simple string to the temporary file using the StreamWriter class:

...

// Write data to the temp file
StreamWriter* writer = File::AppendText(fileName);
writer->WriteLine("Sample data");
writer->Flush();
writer->Close();

This data then can be retrieved via a StreamReader as follows, where you're reading the contents of the entire file into a String object:

StreamReader* reader = File::OpenText(fileName);

Finally, when you're finished using the temporary file, you can delete it via the File::Delete method, where you simply pass the name of the file:

File::Delete(fileName);


About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.

Comments

  • This doesn't work with C++ Visual 2005 edition

    Posted by Alicat on 10/19/2006 02:15pm

    Can someone post some sample code that explains how this can work with Visual C++ 2005 edition?

    Reply
  • An alternative

    Posted by darwen on 02/19/2005 04:57pm

    You could have a 'TemporaryFile' class which creates a temporary file, and then deletes it on finalization.

    • Sure

      Posted by Tom Archer on 02/19/2005 05:33pm

      Absolutely. You can always recreate anything in the BCL. But, why write a class that locates the temp folder and then creates a unique name for you when it's already there?

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: August 13, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT If you are developing applications, you'll want to join us to learn how applications are changing as a result of gesture recognition. This technology will change how you and your users interact - not simply with your devices, but with the world around you. Your devices will be able to see and hear what your users are doing. Are your applications ready for this? Join us to learn about Intel® RealSense™ Technology, including never been …

  • Mobile is introducing sweeping changes throughout your workplace. As a senior stakeholder driving mobile initiatives in your organization, you may be lost in a sea of technologies and claims from vendors promising rapid delivery of applications to your employees, customers, and partners. To help explain some of the topics you will need to be aware of, and to separate the must-haves from the nice-to-haves, this reference guide can help you with applying a mobile strategy in the context of application …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds