CodeGym /Courses /C# SELF /Creating and deleting files

Creating and deleting files

C# SELF
Level 40, Lesson 0
Available

1. Introduction

It might seem that a file is a simple thing and creating it is a piece of cake: just right-click (on Windows). But in real projects programmatic creation and deletion of files is key to automation and flexibility. For example:

  • In a text editor the user hits "Save" — and your code creates a new file where it will write the author's work.
  • An event logging service automatically creates log files when the app starts.
  • An archiver or backup utility regularly creates temporary files and then deletes them.
  • A C# game does autosaves — creating or overwriting a save file.
  • And you (or your script) automatically clean a folder of old temp files so the disk doesn't get cluttered.

Being able to create and delete files automatically is one of the foundational skills of a modern .NET developer.

2. Quick ops via File

Creating a file

In C# you can create a file in different ways. The fastest and simplest way is to use the static class File. Let's try:


// Let's create an empty file "myfile.txt" in the current directory
File.Create("myfile.txt").Close(); // FileStream needs to be closed!
Console.WriteLine("The file 'myfile.txt' has been created.");

Important nuance:
The method File.Create returns a FileStream object that must be closed (Close()) so the OS doesn't complain that the file is "in use". Without closing that stream, some other operations on the same file might unexpectedly fail. Classic case: "The file is being used by another process", even though that "other process" is still your own program that didn't close the stream.

If the file already existed, File.Create will overwrite it (the old one is removed, a new empty one is created in its place). If it didn't exist — it will appear.

So what's the point of an empty file?

Most of the time a new file is wanted not as an empty placeholder but to write something into. For that there are handy methods:

File.WriteAllText("welcome.txt", "Hello, file world!");

This command will create the file, write the string into it, and nicely close the door (the file) behind it so nothing bad happens.

Checking if a file exists

Before creating a new file it's useful to check if it already exists. Otherwise you risk accidentally wiping something important.


if (!File.Exists("important.txt"))
{
    File.WriteAllText("important.txt", "Saving important information.");
    Console.WriteLine("File created.");
}
else
{
    Console.WriteLine("That file already exists, maybe do something else!");
}

3. Real-life example: "Saving a user's greeting"


Console.Write("Enter your name: ");
string name = Console.ReadLine();

string filename = $"{name}_greeting.txt";
string message = $"Welcome, {name}!";

// Check if such a file exists
if (!File.Exists(filename))
{
    File.WriteAllText(filename, message);
    Console.WriteLine($"Personal greeting file {filename} created.");
}
else
{
    Console.WriteLine($"File {filename} already exists! Overwrite? (y/n)");
    string answer = Console.ReadLine();
    if (answer?.ToLower() == "y")
    {
        File.WriteAllText(filename, message);
        Console.WriteLine($"File {filename} overwritten.");
    }
    else
    {
        Console.WriteLine("Leaving everything as is.");
    }
}

What we're doing here:

  • Checking if the file exists (File.Exists).
  • If it doesn't — creating and writing text (File.WriteAllText).
  • If it does — asking the user whether to overwrite.

4. Deleting a file

Deleting files in C# is almost hacker-like... but safe! It's simple too:

Using File.Delete

File.Delete("myfile.txt");

If the file doesn't exist — no drama! Nothing will happen (no error, as long as the path is correct).

Pitfalls for beginners

  • If the file is already open by your program (or someone else), an exception will be thrown.
  • If the path is wrong — you'll get an ArgumentException.

Recommendation: always check existence


if (File.Exists("victim.txt"))
{
    File.Delete("victim.txt");
    Console.WriteLine("File deleted.");
}
else
{
    Console.WriteLine("Nothing to delete — such file not found.");
}

5. Folders and files: creating a file structure

Creating a file inside a folder


string folder = "Data";
Directory.CreateDirectory(folder); // if the folder doesn't exist — it will be created

string filename = Path.Combine(folder, "info.txt");
File.WriteAllText(filename, "A secret message is stored here!");

Important: Attempting to create a file in a non-existent folder will throw an exception. So call Directory.CreateDirectory(folder) first. It won't recreate the folder if it already exists, so the call is safe.

6. Working with instances: FileInfo

For "old-school" and slightly more advanced scenarios the class FileInfo is useful:


FileInfo fi = new FileInfo("example.txt");

// Create a new file (like File.Create — creates an empty file)
using (var fs = fi.Create())
{
    // you can write something if you want
}

Console.WriteLine($"The file 'example.txt' was created using FileInfo.");

Deletion via FileInfo:


FileInfo fi = new FileInfo("oldfile.txt");
if (fi.Exists)
{
    fi.Delete();
    Console.WriteLine("File deleted via FileInfo.");
}

Advantages of FileInfo

If you plan to do more than just create/delete — like frequently access file properties or perform various actions — the instance approach gives convenience (and sometimes a performance win).

7. Creating and cleaning "technical files"

Suppose the app accumulates temporary files in the folder "temp_data", and we want to delete all files in that folder whose names start with "temp_".


string tempFolder = "temp_data";
Directory.CreateDirectory(tempFolder);

for (int i = 1; i <= 5; i++)
{
    string tempFile = Path.Combine(tempFolder, $"temp_{i}.txt");
    File.WriteAllText(tempFile, $"Test data {i}");
}
Console.WriteLine("5 temporary files created.");

// Now delete all temp_*.txt
foreach (string file in Directory.GetFiles(tempFolder, "temp_*.txt"))
{
    File.Delete(file);
    Console.WriteLine($"Deleted file: {file}");
}

Works great for automatically cleaning old and temporary files.

8. Important details: exceptions and safety

What can go wrong:

  • No permission to write/delete in the folder (for example, C:\Windows)
  • The file is already used by another program (or your own!)
  • The path contains invalid characters (for example, *?<>)
  • The file is deleted by another process between your check and delete (yes, that happens!)

How to protect yourself

In production code you should always wrap such operations in a try-catch block:


try
{
    File.Delete("trickyfile.txt");
    Console.WriteLine("File deleted.");
}
catch (UnauthorizedAccessException ex)
{
    Console.WriteLine("No permission to delete the file.");
}
catch (IOException ex)
{
    Console.WriteLine("The file might be used by another process.");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

9. Useful nuances

Files that should always be under control

  • Use Path.Combine to build paths. That way you won't have issues with extra or missing slashes, and your code will be cross-platform.
  • Check file existence before creating/deleting if you don't want surprises.
  • Wrap your code in try-catch if you're working in production and especially in a "multi-user" app.
  • For frequent ops on the same file use FileInfo, for one-off ops — File.
  • Don't keep files open longer than necessary. Have a file open? Ask yourself: "Why?" and close it! Use using where possible.

Technical cheat sheet

Operation Method Note
Create an empty file
File.Create
Returns FileStream, you must close it
Write text to a file
File.WriteAllText
Creates file or overwrites
Check existence
File.Exists
Returns bool
Delete a file
File.Delete
Doesn't throw if the file doesn't exist
Create a file in a folder
Directory.CreateDirectory + File.WriteAllText
Ensures the folder exists
Work with FileInfo
new FileInfo(path).Create / Delete / Exists
For multiple operations

10. Typical mistakes when working with files

Mistake #1: forgetting to close the stream after File.Create.
Many beginners create a file with File.Create but don't close the returned stream. As a result the rest of the code stops "seeing" the file — like it vanished into a parallel universe. Close the stream explicitly (Close()) or use the using construct.

Mistake #2: trying to create a file in a non-existent folder.
A common trap is trying to create a file in a directory that doesn't exist yet. Don't forget to call Directory.CreateDirectory beforehand. It's totally safe: it won't create anything extra, but will ensure the needed folder exists.

Mistake #3: deleting a file without checking.
Sometimes people just call File.Delete without checking for existence. That's allowed — the method won't throw if the file doesn't exist. But if the path is wrong or you don't have access — exceptions are possible. Better handle it in advance.

Mistake #4: confusing File.Delete and Directory.Delete.
File.Delete works only for files, while Directory.Delete is for folders. Trying to delete a folder with File.Delete is like trying to polish a brick with a toothbrush: technically possible but unlikely to be useful.

2
Task
C# SELF, level 40, lesson 0
Locked
Creating and Deleting a File in a Folder
Creating and Deleting a File in a Folder
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION