How to Create a Unique and Temporary Filenames in C# ?

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();
        }     
    }
    
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...