1

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 i.e

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

1
  • head scratching - As the exception tells you, there is no file. No file means no conversion to byte array. Check first with System.IO.File.Exists(pic.FileName); if you file is available. Commented Apr 11, 2018 at 7:47

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

do you have any link please ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.