简体   繁体   中英

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

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

First line of code doesn't convert file to byte array, it just creates a byte array with size of 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 ).

To solve this, you should work with the request's file Stream and write it into byte array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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