How do I clear errno in C#?

Viewed 284

How do I clear errno in .NET Core?

I can read it easily enough by Marshal.GetLastWin32Error() but there's no obvious way to set it or clear it. Google searches were spectacularly useless. Marshal.SetLastError() doesn't exist.

I can't seem to write down a P/Invoke for errno. It's a thread-static native variable.

In case you're wondering why somebody would want to set it, see man 3 readdir. The API specifically calls for setting errno to 0before calling it.

This is what the native code would be:

errno = 0;
struct dirent *entry = readdir(dir);
if (entry == NULL && errno != 0) {
     /* Handle error */
}

So when written as .NET code:

????
IntPtr entry NativeMethods.readdir(dir);
if (entry == IntPtr.Zero && Marshal.GetLastWin32Error() != 0) {
    throw new IOException();
}

If the code where ???? would be is omitted, this gets spurious errors.

I suppose if I get completely stuck I can do something silly like do something that fails with a definite error code and check for that one, but there just aren't that many cases where we can utterly exclude one specific error that's easily generated.

1 Answers
Related