Temporary Files And Directories in C#

Our program demonstrates how to work with temporary files and directories. Here’s the full source code:

using System;
using System.IO;

class TemporaryFilesAndDirectories
{
    static void Check(Exception e)
    {
        if (e != null)
        {
            throw e;
        }
    }

    static void Main()
    {
        // The easiest way to create a temporary file is by
        // using Path.GetTempFileName(). It creates a file and
        // returns its path. The file is created in the default
        // temporary folder for our OS.
        string tempFilePath = Path.GetTempFileName();
        Console.WriteLine("Temp file name: " + tempFilePath);

        // Clean up the file after we're done. The OS is
        // likely to clean up temporary files by itself after
        // some time, but it's good practice to do this
        // explicitly.
        try
        {
            // We can write some data to the file.
            File.WriteAllBytes(tempFilePath, new byte[] { 1, 2, 3, 4 });
        }
        finally
        {
            File.Delete(tempFilePath);
        }

        // If we intend to create many temporary files, we may
        // prefer to create a temporary directory.
        // Path.GetTempPath() returns the path to the temporary folder,
        // and Path.GetRandomFileName() generates a random file name.
        string tempDirPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
        Directory.CreateDirectory(tempDirPath);
        Console.WriteLine("Temp dir name: " + tempDirPath);

        try
        {
            // Now we can create temporary file names by
            // combining them with our temporary directory.
            string tempFilePath2 = Path.Combine(tempDirPath, "file1");
            File.WriteAllBytes(tempFilePath2, new byte[] { 1, 2 });
        }
        finally
        {
            // Clean up the directory and all its contents
            Directory.Delete(tempDirPath, true);
        }
    }
}

To run the program, save it as TemporaryFilesAndDirectories.cs and use the C# compiler to build and run it:

$ csc TemporaryFilesAndDirectories.cs
$ mono TemporaryFilesAndDirectories.exe
Temp file name: /tmp/tmp9B1C.tmp
Temp dir name: /tmp/13q1qhba.3ln

Note that the exact file and directory names will be different each time you run the program, as they are generated randomly to ensure uniqueness.

查看推荐产品

Comments powered by Disqus