Home > Net >  How do I write to file descriptor 3 instead of stdout in .NET 6 on Linux?
How do I write to file descriptor 3 instead of stdout in .NET 6 on Linux?

Time:11-08

I'm using .NET 6 on Ubuntu 22.04. What is the equivalent C# code to the following Bash code?

echo 'Hello, World!' >&3

Normally, in C# I'd use code like Console.WriteLine("Hello, World!"); to write to stdout. But here, I need to write to file descriptor 3 instead of stdout.

I was able to find some Stack Overflow answers, but they're quite old and deal with Windows APIs which I don't think applies to what I'm trying to do.

I should clarify too that for my use case, redirecting standout output to another file descriptor as I start the .NET process isn't an option. This is is because I need to be able to write to stdout for one purpose, stderr for another, and file descriptor 3 for another. Three purposes in total. This is because the process must be able to be started by a framework that deals with stdout, stderr, and file descriptor 3 these ways. It needs to be compatible.

CodePudding user response:

You should be able to achieve this by writing to /proc/self/fd/3

Use a StreamWriter:

using (StreamWriter outputFile = new StreamWriter("/proc/self/fd/3"))
{
    outputFile.WriteLine("Test");
}

Otherwise, you could make a system call to echo, using the command you referenced above, or this...

Process.Start(@"echo Test > /proc/self/fd/3");
  • Related