当内容类型为application / octet-stream时,如何打印Stream的内容?

时间:2014-02-06 17:00:08

标签: c# text mime-types remoting

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

基本上,在监视窗口中,我可以看到在运行代码后已为我的变量赋值: - enter image description here

但是如果我打开Text Visualizer它就是空的。 同样,如果我尝试将字符串写入“输出”窗口,则不会写入任何行。

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

    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;
    }

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

request = request.Replace("\0", "");

我现在在输出窗口中得到这个,非常适合我的目的,谢谢。

----------请求标题-----------

__ ConnectionId:16

__ IPAddress:127.0.0.1

__ RequestUri:/VisaOM.Server.ClientServices.Services

Content-Type:application / octet-stream

__ CustomErrorsEnabled:False

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

get_SecurityServiceszVisaOM.Client.Services.IServices,VisaOM.Client.Services.Interfaces, Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null

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