-6

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

Nobody
  • 1
  • 3
  • what's wrong with [File.Delete](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.delete?view=net-6.0)? could you please elaborate what _problem_ you're trying to solve? i recommend [taking the tour](https://stackoverflow.com/tour), as well as reading [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [what's on topic](https://stackoverflow.com/help/on-topic). – Franz Gleichmann Jan 26 '22 at 21:43
  • Does this answer your question? [How to delete a file after checking whether it exists](https://stackoverflow.com/questions/6391711/how-to-delete-a-file-after-checking-whether-it-exists) Don't mind that the post also includes "after checking...", this question is so fundamental that there isn't going to be an existing post for just that. – gunr2171 Jan 26 '22 at 21:46
  • 3
    .NET already uses the most efficient and proven way, it uses a [native function](https://referencesource.microsoft.com/#mscorlib/system/io/file.cs,303). Necessarily so, deleting a file is an OS operation and the OS is native. – Hans Passant Jan 26 '22 at 22:08

1 Answers1

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