How to Copy , Delete File in C#
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.
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 );
}
}
}
}
Related Topics
- How to write a text file in c#
- Append text to an existing file in C#
- How to use C# Directory Class
- How to use C# File Class
- How to use C# FileStream Class
- How to use C# Textreader Class
- A simple C# Text Reader source code
- How to use C# TextWriter Class
- How to use C# BinaryWriter Class
- How to use C# BinaryReader Class
- How to convert XPS file to Bitmap
- How to C# Path Class
- How to create a pdf file in C#
- How to create PDF file from Text file
- Write Database data to pdf file
Related Topics