In this example, you will see how to delete, copy and move a single file from a hard disk using C#/ VB.NET. You can delete, copy and move a file using System.IO.File class which is inherited from System.IO.
Following example shows how to delete a file from a hard disk.
C#
public static bool Delete(string fileName)
{
try
{
System.IO.File.Delete(fileName);
return true;
}
catch
{
//File not exists or hard disk failure.
return false;
}
}
public static bool Move(string oldFilename,string newFilename)
{
try
{
System.IO.File.Move(oldFilename,newFilename );
return true;
}
catch
{
//File not exists or hard disk failure.
return false;
}
}
public static bool Copy(string oldFilename, string newFilename)
{
try
{
System.IO.File.Copy(oldFilename, newFilename);
return true;
}
catch
{
//File not exists or hard disk failure.
return false;
}
}
VB.NET
Public Shared Function Delete(fileName As String) As Boolean
Try
System.IO.File.Delete(fileName)
Return True
Catch
'File not exists or hard disk failure.
Return False
End Try
End Function
Public Shared Function Move(oldFilename As String, newFilename As String) As Boolean
Try
System.IO.File.Move(oldFilename, newFilename)
Return True
Catch
'File not exists or hard disk failure.
Return False
End Try
End Function
Public Shared Function Copy(oldFilename As String, newFilename As String) As Boolean
Try
System.IO.File.Copy(oldFilename, newFilename)
Return True
Catch
'File not exists or hard disk failure.
Return False
End Try
End Function
C#
if (Delete("@c:\notepad.txt"))
{
//File deleted successfully
}
else
{
//File not exists
}
if (Move("@c:\notepad.txt","@D:\notepad.txt"))
{
//File moved successfully
}
else
{
//File not exists
}
if (Copy("@c:\notepad.txt", "@D:\notepad.txt"))
{
//File copied successfully
}
else
{
//File not exists
}
Note:
- .NET Framework does not support all versions of platform, for more information click here.
- System.IO.FileNotFoundException class throw when file not exist on disk.