C# 在重定向stdout时写入stderr以响应Console.CancelKeyPress

C# 在重定向stdout时写入stderr以响应Console.CancelKeyPress,c#,.net,C#,.net,当我运行下面的程序并点击ctrl+C时,当stdout被重定向时,它不会写入任何内容 > .\ConsoleApplication2.exe Cancelled by user. > .\ConsoleApplication2.exe > foo.txt > 这有什么办法吗 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.

当我运行下面的程序并点击ctrl+C时,当stdout被重定向时,它不会写入任何内容

> .\ConsoleApplication2.exe
Cancelled by user.
> .\ConsoleApplication2.exe > foo.txt
>
这有什么办法吗

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.CancelKeyPress += Console_CancelKeyPress;

            Thread.Sleep(TimeSpan.FromMinutes(1));
        }

        static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            Console.Error.WriteLine("Cancelled by user.");
        }
    }
}

我不能用你的代码复制它。它仍然被用户取消写入。当我按下ctrl-c并使用>foo.txt重定向时,返回控制台。@Dirk您使用的是Powershell还是cmd.exe?当我使用cmd.exe时,它似乎可以工作。可能这是一个Powershell错误。我使用的是cmd.exe控制台。使用Powershell我可以复制它。但是从我刚刚读到的文档来看,只有在使用2>时才应该重定向stderr。我也无法准确地复制和编译您的代码。您可能需要测试Console.IsErrorRedirected属性,看看这是否能说明问题。