在c#中将二进制文件保存到ram

时间:2017-06-29 13:24:10

标签: c#

我正在为移动设备开发一个闪存工具,它可以将加载程序发送给它 communications.currently我通过URL的web请求收到loader文件 并将其存储在磁盘中。下面是我使用的代码

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中 然后从那里使用它 到目前为止,我试图使用内存流没有结果。

1 个答案:

答案 0 :(得分:0)

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
    ...
}