---
title: "How do you delete a file in C#?"  
description: "How do you delete a file in C#?"  
author: "ICSM Computer"  
published: 2025-05-06  
updated: 2025-05-19  
canonical: https://www.mindstick.com/forum/161578/how-do-you-delete-a-file-in-c-sharp  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 1 minute  

---

# How do you delete a file in C#?

How do you [delete a file in C](https://answers.mindstick.com/qa/104760/how-to-delete-a-file-in-c)#? [Explain](https://www.mindstick.com/forum/157854/what-is-system-debugging-explain-some-system-debugging-tools-used-in-modern-computer-systems) with example.

## Replies

### Reply by Anubhav Sharma

To **[delete](https://www.mindstick.com/forum/33620/how-to-delete-record-from-list-in-mvc-using-ajax) a [file in C#](https://www.mindstick.com/forum/159903/how-to-create-a-log-file-in-c-sharp)**, use the `File.Delete()` method from the `System.IO` namespace.

### Syntax:

```cs
File.Delete(string path);
```

`path`: The full path of the file to delete.

### Example:

```cs
using System.IO;

string filePath = @"C:\example\myfile.txt";

if (File.Exists(filePath))
{
    File.Delete(filePath);
    Console.WriteLine("File deleted.");
}
else
{
    Console.WriteLine("File not found.");
}
```

### Notes:

1. **No exception** is thrown if the file doesn’t exist — unless you try to access it afterward.
2. Will throw exceptions like:

   1. `UnauthorizedAccessException`: If you don't have permission.
   2. `IOException`: If the file is in use by another process.
   3. `ArgumentException` / `PathTooLongException`: If the path is invalid.

### Optional: Safe delete with try-catch

```cs
try
{
    if (File.Exists(filePath))
        File.Delete(filePath);
}
catch (Exception ex)
{
    Console.WriteLine("Error deleting file: " + ex.Message);
}
```


---

Original Source: https://www.mindstick.com/forum/161578/how-do-you-delete-a-file-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
