DeleteFile (kernel32)
Last changed: -188.21.234.130

.
Summary

C# Signature:

[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);

User-Defined Types:

None.

Notes:

I couldn't get DeleteFile to work on Windows XP - I always get a return code of 2 (File not found). I used DeleteFileW instead.

Tips & Tricks:

Please add some!

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);
}

Alternative Managed API:

System.IO.File:

public static void Delete(string path);

Documentation
DeleteFile on MSDN