目前我在创建文件时遇到问题,我正在尝试使用streamWriter类编写文本内容,但我没有得到预期的答案.. 以下是我的示例代码: -
我的c#代码如下: -
public void ProcessRequest(HttpContext context)
{
// Create a connexion to the Remote Server to redirect all requests
RemoteServer server = new RemoteServer(context);
// Create a request with same data in navigator request
HttpWebRequest request = server.GetRequest();
// Send the request to the remote server and return the response
HttpWebResponse response = server.GetResponse(request);
context.Response.AddHeader("Content-Disposition", "attachment; filename=playlist.m3u8");
context.Response.ContentType = response.ContentType;
Stream receiveStream = response.GetResponseStream();
var buff = new byte[1024];
int bytes = 0;
string token = Guid.NewGuid().ToString();
while ((bytes = receiveStream.Read(buff, 0, 1024)) > 0)
{
//Write the stream directly to the client
context.Response.OutputStream.Write(buff, 0, bytes);
context.Response.Write("&token="+token);
}
//close streams
response.Close();
context.Response.End();
}
上面代码的输出如下: -
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=20776,CODECS="avc1.66.41",RESOLUTION=320x240
chunk.m3u8?nimblesessionid=62
&token=42712adc-f932-43c7-b282-69cf349941da
但我的预期输出是: -
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=20776,CODECS="avc1.66.41",RESOLUTION=320x240
chunk.m3u8?nimblesessionid=62&token=42712adc-f932-43c7-b282-69cf349941da
我只想在相同的行中使用该令牌参数而不是新行..
谢谢。
答案 0 :(得分:2)
如果您只想在收到的字节末尾删除换行符,请更改while
循环中的代码,如下所示:
while ((bytes = receiveStream.Read(buff, 0, 1024)) > 0)
{
if (buff[bytes-1] == 0x0a)
bytes -= 1;
//Write the stream directly to the client
context.Response.OutputStream.Write(buff, 0, bytes);
context.Response.Write("&token="+token);
}
有几点需要注意:
0x0a
(换行符,'\n'
作为字符)位于您接收的字节的末尾时,它才有效。如果由于某种原因,服务器发送的消息是在几个块中接收的,那么首先必须确保在检查最后一个字节之前收到了要接收的所有内容。
另请注意,这会在当前代码中生成多个&token=...
行。0x0d
或'\r'
)作为行结束字节,甚至两者都使用。检查服务器发送的内容并相应地调整代码。