当前我在创建文件时面临问题,我正在尝试使用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
我只是想在同一行中而不是新行中的象征参数。
谢谢。
如果您只想在接收到的字节末尾删除新线,请更改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
(newline字节,'n'
作为字符(处于字节末尾,您才能使用。如果由于某种原因,服务器发送的消息是在几个块中收到的,则首先必须确保在检查最后一个字节之前收到的所有内容。另请注意,这将导致当前代码中的多个&token=...
行。 - 根据服务器的不同,它可能使用马车返回(
0x0d
或'r'
(作为线路结束字节,甚至两者兼而有之。检查服务器发送的内容并相应地调整代码。