想要 select 来自服务器路径的图像并将其转换为二进制形式

want to select image from server path and convert it to binary form

public class AdminController : Controller
   {
       public HHCCEntities hc = new HHCCEntities();
       public ActionResult ServicesView()
    {
        var x = hc.Services.ToList();
        return View(x);
    }
    [Authorize]
    public ActionResult AddServices(int id = 0)
    {

        if (id == 0)
        {
            return View(new Service());
        }
        else
        {
            Service s = new Service();
            HttpResponseMessage response = 
GlobalVariables.webapiclient.GetAsync("Services/" + id.ToString()).Result;
            s = response.Content.ReadAsAsync<Service>().Result;
            return View(s);

        }

    }
     private byte[] GetBinaryFile(string filename)
    {
        byte[] bytes;
        using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
        {
            bytes = new byte[file.Length];
            file.Read(bytes, 0, (int)file.Length);
        }
        return bytes;
    }
    [Authorize]
    [HttpPost]
    public ActionResult AddServices(Service s, HttpPostedFileBase ImageFile)
    {
        if (ImageFile != null)
        {
            s.Simage = new byte[ImageFile.ContentLength];
            ImageFile.InputStream.Read(s.Simage, 0, ImageFile.ContentLength);
        }
        if (s.ID==0)
        {
            if (ImageFile == null)
            {

                string filename = "MVC_WEBAPI\images\patient.png";

这里我想要一些代码 select 来自服务器路径的图像并将其转换为二进制流。

变量文件名包含已保存在服务器中的图像的路径。

此路径抛出错误。

我的问题是如何为存储在项目中的图像文件夹中的图像获取正确的正确路径?

               byte[] bytes = GetBinaryFile(filename);

            }
            HttpResponseMessage response = GlobalVariables.webapiclient.PostAsJsonAsync("Services", s).Result;
        }
        else
        {
            HttpResponseMessage response = GlobalVariables.webapiclient.PutAsJsonAsync("Services/" + s.ID, s).Result;
        }
        return View();
    }
}

}

您可以编写自己的函数:

private byte[] GetBinaryFile(filename)
{
     byte[] bytes;
     using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read))
     {
          bytes = new byte[file.Length];
          file.Read(bytes, 0, (int)file.Length);
     }
     return bytes;
}

然后您可以从您的控制器操作中调用该函数:

byte[] bytes = GetBinaryFile("filename.bin");

你也可以把它扔到 Stream:

Stream stream = new MemoryStream(bytes);

编辑

我不确定为什么会出现错误,但是有一个更短的版本可以将文件读入二进制数据。你能试试这个吗?

byte[] bytes = System.IO.File.ReadAllBytes("Stuff\file.exe");
          if (ImageFile == null)
               {  
                string filename = "/images/Services.png";
                var dir = Server.MapPath(filename);
                byte[] bytes = System.IO.File.ReadAllBytes(dir);
                s.Simage = bytes;
               }
    HttpResponseMessage response = 
GlobalVariables.webapiclient.PostAsJsonAsync("Services", s).Result;