gpt4 book ai didi

c# - 从基本流 (httpRequestStream) 读取

转载 作者:太空狗 更新时间:2023-10-29 22:23:54 27 4
gpt4 key购买 nike

我有一个基本流,它是 HTTP 请求流和

var s=new HttpListener().GetContext().Request.InputStream;

我想读取流(其中包含非字符内容,因为我已经发送了数据包)

当我们用 StreamReader 包装这个流然后我们使用 StreamReader 的 ReadToEnd() 函数它可以读取整个流并返回一个字符串...

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://127.0.0.1/");
listener.Start();
var context = listener.GetContext();
var sr = new StreamReader(context.Request.InputStream);
string x=sr.ReadToEnd(); //This Workds

但因为它有非字符内容,我们不能使用 StremReader(我尝试了所有编码机制..使用字符串是错误的)。我不能使用函数

context.Request.InputStream.Read(buffer,position,Len) 

因为我无法获取流的长度,InputStream.Length 总是抛出异常并且无法使用..我不想创建像 [size][file] 这样的小协议(protocol)并先读取大小然后再读取文件。 ..不知何故 StreamReader 可以获得长度..我只是想知道如何。这个我也试过了,还是不行

List<byte> bb = new List<byte>();
var ss = context.Request.InputStream;
byte b = (byte)ss.ReadByte();
while (b >= 0)
{
bb.Add(b);
b = (byte)ss.ReadByte();
}

我已经通过以下方法解决了

FileStream fs = new FileStream("C:\\cygwin\\home\\Dff.rar", FileMode.Create);
byte[] file = new byte[1024 * 1024];
int finishedBytes = ss.Read(file, 0, file.Length);
while (finishedBytes > 0)
{
fs.Write(file, 0, finishedBytes);
finishedBytes = ss.Read(file, 0, file.Length);
}
fs.Close();

谢谢乔恩,道格拉斯

最佳答案

您的错误在于以下行:

byte b = (byte)ss.ReadByte();

byte类型是无符号的;什么时候 Stream.ReadByte 在流的末尾返回 -1,您不加选择地将其转换为 byte ,将其转换为 255,因此满足 b >= 0健康)状况。值得注意的是返回类型是 int , 不是 byte ,正是出于这个原因。

代码的快速修复:

List<byte> bb = new List<byte>();
var ss = context.Request.InputStream;
int next = ss.ReadByte();
while (next != -1)
{
bb.Add((byte)next);
next = ss.ReadByte();
}

以下解决方案更有效,因为它避免了 ReadByte 引起的逐字节读取。调用,并为 Read 使用一个动态扩展的字节数组而是调用(类似于 List<T> 的内部实现方式):

var ss = context.Request.InputStream;

byte[] buffer = new byte[1024];
int totalCount = 0;

while (true)
{
int currentCount = ss.Read(buffer, totalCount, buffer.Length - totalCount);
if (currentCount == 0)
break;

totalCount += currentCount;
if (totalCount == buffer.Length)
Array.Resize(ref buffer, buffer.Length * 2);
}

Array.Resize(ref buffer, totalCount);

关于c# - 从基本流 (httpRequestStream) 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8870101/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com