Search code examples
c#.netwindowsnative-methods

Effective Way to Delete File using Native Methods in C#


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


Solution

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