C# 当内容类型为application/octet Stream时,如何打印流的内容?

C# 当内容类型为application/octet Stream时,如何打印流的内容?,c#,text,mime-types,remoting,C#,Text,Mime Types,Remoting,我试图通过实现ServerChannelSink来拦截.NET远程处理请求/响应。 除了我似乎无法将流解码为字符串之外,一切都很好。我该怎么做 基本上,在“监视”窗口中,我可以看到在运行代码后,已为我的变量分配了一个值:- 但是如果我打开文本可视化工具,它是空的。 类似地,如果我尝试将字符串写入输出窗口,则不会写入任何行 以下是我正在使用的代码: private static void PrintStream(TextWriter output, ref Stream stream)

我试图通过实现ServerChannelSink来拦截.NET远程处理请求/响应。 除了我似乎无法将流解码为字符串之外,一切都很好。我该怎么做

基本上,在“监视”窗口中,我可以看到在运行代码后,已为我的变量分配了一个值:-

但是如果我打开文本可视化工具,它是空的。 类似地,如果我尝试将字符串写入输出窗口,则不会写入任何行

以下是我正在使用的代码:

    private static void PrintStream(TextWriter output, ref Stream stream)
    {
        // If we can't reset the stream's position after printing its content,
        //   we must make a copy.
        if (!stream.CanSeek)
            stream = CopyStream(stream);

        long startPosition = stream.Position;

        byte[] buffer = new byte[stream.Length];

        stream.Read(buffer, 0, (int)stream.Length);

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

        string request = enc.GetString(buffer, 0, buffer.Length);

        output.WriteLine(request);

        output.WriteLine();

        // set stream to previous position for message processing

        stream.Seek(startPosition, SeekOrigin.Begin);
    }
我也尝试过使用StreamReader,但效果相同:

    private static void PrintStream(TextWriter output, ref Stream stream)
    {
        // If we can't reset the stream's position after printing its content,
        //   we must make a copy.
        if (!stream.CanSeek)
            stream = CopyStream(stream);

        long startPosition = stream.Position;

        StreamReader sr = new StreamReader(stream);
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            output.WriteLine(line);
        }

        stream.Position = startPosition;
    }

应用程序/octet流
表示二进制。您的请求变量只包含二进制数据,其中一些数据会转换为人类可读的文本,因此您无法将其转换为字符串


您最好使用
Convert.ToBase64String
将其转换为base 64,但它不是人类可读的。将其转换为ASCII将损坏数据。

多亏paqogomez关于
\0
的回答被解释为字符串的结尾,我刚刚添加了以下内容:-

request = request.Replace("\0", "");
我现在在输出窗口中得到了这个,非常适合我的目的,谢谢

----------请求头-----------

__连接ID:16

__IP地址:127.0.0.1

__RequestUri:/VisaOM.Server.ClientServices.Services

内容类型:应用程序/八位字节流

__CustomErrorsEnabled:False

----------请求消息-----------

获取_SecurityServiceszVisaOM.Client.Services.IServices、VisaOM.Client.Services.Interfaces、, 版本=1.0.0.0,区域性=中立,PublicKeyToken=null


------请求结束消息-----

您已经过了吗?由于那些
\0
的原因,它不会显示在文本可视化工具中
\0
是空字符,通常表示unicode(utf8)字符串的结尾。感谢您的回答。我只是对在手表窗口中看到的可读文本感兴趣。根据paqogomez的观察,我在下面发布了一个解决方案,\0被勇敢地称为字符串的结尾。