How to Copy , Delete File in C#

The File class in the System.IO namespace provides a range of useful functionalities for working with files in C# applications. The File class is a versatile tool for working with files in C# applications, offering a convenient and efficient way to perform various file-related operations.

When working with files, it is important to handle potential exceptions that may occur. The FileNotFoundException class is thrown when an attempt is made to access a file that does not exist on disk. This exception can be caught and handled to gracefully respond to the absence of the expected file.

File.Copy("c:\\temp.txt", "c:\\copytemp.txt", true); File.Delete("c:\\copytemp.txt");

IOException class

The IOException class serves as the base class for exceptions thrown while accessing information using streams, files, and directories. It encompasses a range of exceptions that can occur during file operations, such as read/write errors, disk full errors, and other I/O-related issues. Handling IOException and its derived exceptions allows for effective error handling and resilience in file-related operations.

try { //code here } catch (System.IO.FileNotFoundException ex) { //exception here }

The following C# program shows how to use File Class for copying and deleting a text file and also its shows how to handle System.IO.FileNotFoundException Class.

Full Source C#
using System; using System.Windows.Forms; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { File.Copy("c:\\temp.txt", "c:\\copytemp.txt", true); File.Delete("c:\\copytemp.txt"); } catch (System.IO.FileNotFoundException ex) { MessageBox.Show(ex.StackTrace ); } } } }


Using the capabilities of the File class and handling potential exceptions, developers can work with files effectively, retrieve file attributes and DateTime information, and perform common file operations in their C# applications.