在流数据中查找特定字符串
如果在流中查找字符串,需要设置一个大小适中的缓存,
static void Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add(“http://localhost:8081/ListenerTest/");
listener.Start();
while (1==1)
{
HttpListenerContext context = listener.GetContext();
Task.Run(() =>
{
if (context.Request.HttpMethod == “POST”)
{
SaveFile(context.Request.ContentEncoding, GetBoundary(context.Request.ContentType),
context.Request.InputStream);
}
context.Response.StatusCode = 200;
context.Response.ContentType = “text/html”;
context.Response.AddHeader(“Access-Control-Allow-Origin”, “*”);
using (StreamWriter writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
writer.WriteLine(“File Uploaded”);
context.Response.Close();
});
}
listener.Stop();
}
private static String GetBoundary(String ctype)
{
return “--“ + ctype.Split(‘;’)[1].Split(‘=’)[1];
}
//之前没找到boundary是因为我没有调用getboundary,直接把contenttype穿过去了
private static string SaveFile(Encoding enc, String contentType, Stream input)
{
Byte[] boundaryBytes = enc.GetBytes(GetBoundary(contentType));
Int32 boundaryLen = boundaryBytes.Length;
string fileName = Guid.NewGuid().ToString(“N”) + “.temp”;
using (FileStream output = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
Byte[] buffer = new Byte[1024];
Int32 len = input.Read(buffer, 0, 1024);
Int32 startPos = -1;
// Find start boundary
while (true)
{
if (len == 0)
{
throw new Exception(“Start Boundaray Not Found”);
}
startPos = IndexOf(buffer, len, boundaryBytes);
if (startPos >= 0)
{
break;
}
else
{
Array.Copy(buffer, len - boundaryLen, buffer, 0, boundaryLen);
len = input.Read(buffer, boundaryLen, 1024 - boundaryLen);
}
}
// Skip four lines (Boundary, Content-Disposition, Content-Type, and a blank)
for (Int32 i = 0; i < 4; i++)
{
while (true)
{
if (len == 0)
{
throw new Exception(“Preamble not Found.”);
}
startPos = Array.IndexOf(buffer, enc.GetBytes(“\n”)[0], startPos);
if (startPos >= 0)
{
startPos++;
break;
}
else
{
len = input.Read(buffer, 0, 1024);
}
}
}
Array.Copy(buffer, startPos, buffer, 0, len - startPos);
len = len - startPos;
while (true)
{
Int32 endPos = IndexOf(buffer, len, boundaryBytes);
if (endPos >= 0)
{
if (endPos > 0) output.Write(buffer, 0, endPos - 2);
break;
}
else if (len <= boundaryLen)
{
throw new Exception(“End Boundaray Not Found”);
}
else
{
output.Write(buffer, 0, len - boundaryLen);
//每次放置后40个字节到首部,读取接下来984个字节,在此基础上进行byte查找,绝妙!
Array.Copy(buffer, len - boundaryLen, buffer, 0, boundaryLen);
len = input.Read(buffer, boundaryLen, 1024 - boundaryLen) + boundaryLen;
}
}
}
return fileName;
}