将二进制文件保存到C#中的RAM



我正在为手机开发闪光灯工具,该工具将加载程序发送给它以供进一步communications.concly,我从URL通过Web请求接收加载程序文件并将其存储在磁盘中.below是我使用的代码

private void submitData()
    {
        try
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            string cpuid = comboBox1.Text;
            string postdata = "cpuid=" + cpuid;
            byte[] data = encoding.GetBytes(postdata);
            WebRequest request = WebRequest.Create("Http://127.0.0.1/fetch.php");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();
            WebResponse response = request.GetResponse();
            stream = response.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            string path = sr.ReadToEnd();
            MessageBox.Show(path);
            DateTime startTime = DateTime.UtcNow;
            WebRequest request1 = WebRequest.Create("http://127.0.0.1/"+path);
            WebResponse response2 = request1.GetResponse();
            using (Stream responseStream = response2.GetResponseStream())
            {
                using (Stream fileStream = File.OpenWrite(@"e:loader.mbn"))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead = responseStream.Read(buffer, 0, 4096);
                    while (bytesRead > 0)
                    {
                        fileStream.Write(buffer, 0, bytesRead);
                        DateTime nowTime = DateTime.UtcNow;
                        if ((nowTime - startTime).TotalMinutes > 1)
                        {
                            throw new ApplicationException(
                                "Download timed out");
                        }
                        bytesRead = responseStream.Read(buffer, 0, 4096);
                    }
                    MessageBox.Show("COMPLETDED");
                }
            }
            sr.Close();
            stream.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show("ERR :" + ex.Message);
        }

我的问题是有一种方法可以将文件直接存储到RAM然后从那里使用到目前为止,我尝试使用内存流而没有结果。

MemoryStream没有错。如果您想使用数据,则必须记住将流的位置重置为开始。

//If the size is known, use it to avoid reallocations
use(var memStream=new MemoryStream(response.ContentLength))
use(var responseStream=response.GetResponseStream())
{
    //Avoid blocking while waiting for the copy with CopyToAsync instead of CopyTo
    await responseStream.CopyToAsync(memStream);
    //Reset the position
    memStream.Position = 0;
    //Use the memory stream
    ...
}

最新更新