繁体   English   中英

无法转换字节数组中的文件

[英]Unable to convert file in byte array

当我尝试使用此代码将文件转换为字节数组时,我有一个问题

var fileByte = new byte[pic.ContentLength];

它会转换文件,但是当文件上传时它会被破坏。 当我尝试另一个代码来转换文件,即

   var pic = System.Web.HttpContext.Current.Request.Files["ImagePath"];
   byte[] bytes = System.IO.File.ReadAllBytes(pic.FileName);

它抛出了一个例外

找不到文件'C:\\ Program Files \\ IIS Express \\ slide2.jpg'。

在我试过这个词之后

byte[] b = StreamFile(pic.FileName);

private byte[] StreamFile(string filename)
    {
        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);

        Create a byte array of file stream length
        byte[] ImageData = new byte[fs.Length];

        //Read block of bytes from stream into the byte array
        fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

        //Close the File Stream
        fs.Close();
        return ImageData; //return the byte data
    }

但它也抛出和异常一样

找不到文件'C:\\ Program Files \\ IIS Express \\ slide2.jpg'。

第一行代码不会将文件转换为字节数组,它只是创建一个大小为pic.ContentLength的字节数组。

第二个示例抛出一个异常,该异常清楚地表明您没有指定路径上的图像(由pic.FileName定义)。

要解决此问题,您应该使用请求的文件Stream并将其写入字节数组。

var pic = System.Web.HttpContext.Current.Request.Files["ImagePath"];
byte[] bytes;
using (var stream = new MemoryStream())
{
   pic.InputStream.CopyTo(stream);
   bytes = stream.ToArray();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM