Skip to main content

Helper function to generates a random temporary file name, with a specified file extension and optional path prefix.

/// <summary>
/// Generates a random temporary file name, with a specified <paramref name="fileExtension"/> and optional <paramref name="pathPrefix"/>.
/// </summary>
/// <param name="fileExtension">A file extension for the generated file name.</param>
/// <param name="pathPrefix">Specify a path that will be prepended to the generated file name. If <paramref name="pathPrefix"/> is <see langword="null"/>, the current user's temporary folder will be used.</param>
/// <returns>An absolute path to the generated temp file name.</returns>
public static string GetTempFileName(string fileExtension, string pathPrefix = null)
{
    if (fileExtension == null)
    {
        fileExtension = "";
    }

    if (pathPrefix == null)
    {
        try
        {
            pathPrefix = Path.GetTempPath();
        }
        catch (SecurityException)
        {
            Debug.WriteLine(
                "Caller does not have the appropriate permissions " +
                "to access current user's temporary file path. " +
                "The path prefix will be set to \".\", or the current " +
                "working directory.");

            pathPrefix = ".";
        }
    }

    var fileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + fileExtension;

    return Path.Combine(pathPrefix, fileName);
}