简体   繁体   English

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

[英]Unable to convert file in byte array

i have an issue when i am trying to convert a file into byte array using this code 当我尝试使用此代码将文件转换为字节数组时,我有一个问题

var fileByte = new byte[pic.ContentLength];

it converts the file but when file is uploaded it is corrupted. 它会转换文件,但是当文件上传时它会被破坏。 and when i tried the another code to convert the file ie 当我尝试另一个代码来转换文件,即

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

it thrown an exception like 它抛出了一个例外

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

after words i'd tried for this 在我试过这个词之后

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
    }

but it also throw and exception like 但它也抛出和异常一样

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

First line of code doesn't convert file to byte array, it just creates a byte array with size of pic.ContentLength . 第一行代码不会将文件转换为字节数组,它只是创建一个大小为pic.ContentLength的字节数组。

Second example throws you an exception which clearly states that you don't have the image on specified path (defined by pic.FileName ). 第二个示例抛出一个异常,该异常清楚地表明您没有指定路径上的图像(由pic.FileName定义)。

To solve this, you should work with the request's file Stream and write it into byte array. 要解决此问题,您应该使用请求的文件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