Is this PInvoke code correct and reliable?

前端 未结 3 1567
名媛妹妹
名媛妹妹 2020-12-15 18:05

In this question I have searched for a simple solution to unblock files. Thanks to all the comments and answer, I have found a simple solution by PInvoking DeleteFile

3条回答
  •  时光取名叫无心
    2020-12-15 18:28

    Calling the native method will never raise an exception. If the file deletion fails, for whatever reason, the call to DeleteFile returns false.

    Your P/Invoke code is good. You are correctly using Unicode characters, setting SetLastError to true and the parameter marshalling is correct. To check for errors look for the value of the boolean return from DeleteFile. If it is false (i.e. the call failed) then call Marshal.GetLastWin32Error to find out the Win32 error code.

    The most obvious causes for the function to fail are:

    1. The file does not exist.
    2. The alternate stream is not present.
    3. The process does not have sufficient rights to delete the alternate stream.

    For 1 and 2 an error code of ERROR_FILE_NOT_FOUND will be returned. For 3 you will be given an error code of ERROR_ACCESS_DENIED.

提交回复
热议问题