.NET 11 Preview - Getting A Handle To The NULL Device
[C#, .NET, .NET 11 Preview]
When working with files or streamed data, there are times when you want to signal that you don’t care about where the data is going.
It is on these occasions that you use the NULL device.
On Linux, this is /dev/null
On Windows, this is NUL
Take a scenario where you want to capture the contents of a file listing to a file, using the ls command.
ls > list.txt
This will work on Unix, macOS, and Linux, on most shells (bash, fish, zsh, etc).
It will also work on Windows if you are using PowerShell.
The case arises of what to do when you don’t care about the results.
In which case you would do the following:
On Unix, macOS, and Linux:
ls > /dev/null
On Windows:
ls > NUL
Is it possible to do this programmatically?
Yes.
In .NET 11, you can now do this easily via the new OpenNullHandle API in the File class.
You use it like this:
using (var handle = File.OpenNullHandle())
{
// Can now use handle in here
}
TLDR
The OpenNullHandle method in the File class allows you to get a handle to the system NULL device.
Happy hacking!