Sometimes you may want to create an temporary file . Instead of manipulating the user’s temporary directory and then manually generating the random file name , you can use the GetTempFileName method defined in the Path class.
If you don’t need to create the file , you can use the Path.GetRandomFileName() instead.
How to Create a Unique and Temporary Filenames in C# ?
Below is a sample code snippet demonstrating how to create a temporary file and write a text to it.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.IO;
namespace GinktageConsoleApp
{
internal class Program
{
private static void Main(string[] args)
{
string tempFileName = Path.GetTempFileName();
using (StreamWriter streamWriter = File.CreateText(tempFileName))
{
streamWriter.WriteLine("Welcome to Ginktage");
}
Console.ReadLine();
}
}
}