The File class we can use to get and set file attributes or DateTime information related to the creation, access, and writing of a file. Also we can use File class for copying, moving, delete , renaming etc. to file.
File.Copy("c:\\temp.txt", "c:\\copytemp.txt", true);
File.Delete("c:\\copytemp.txt");
FileNotFoundException Class is throw the exception when an attempt to access a file that does not exist on disk fails. IOException is the base class for exceptions thrown while accessing information using streams, files and directories.
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.
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 );
}
}
}
}