Effective Way to Delete File using Native Methods in C#

525 Views Asked by At

I am looking for a way to delete files using Native Methods in the most efficient and proven way in C#

1

There are 1 best solutions below

3
specilist5677 On BEST ANSWER
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DeleteFile(string lpFileName);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DeleteFileA([MarshalAs(UnmanagedType.LPStr)]string lpFileName);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DeleteFileW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName);

Use DeleteFileW for Unicode names and DeleteFileA for ANSI names. Sample Code:

String filePath = @"C:\Data\MyFile.txt";

bool deleted = DeleteFileW(filePath);
if (!deleted)
{
     int lastError = Marshal.GetLastWin32Error();
     Console.WriteLine("Failed to delete '{1}': error={0}", lastError, filePath);
}