.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Code Snippets >> File Operation >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Convert file into byte array

Posted By:Pankaj Mishra       Posted Date: August 06, 2008    Points: 10    Category: File Operation    URL: http://www.dotnetspark.com  

Below method is used to convert a file .gif, .jpg, .Doc, .txt or any type of file to its byte array

This function is used to convert file into byte array. some time we require to convert file into byte to save into database or send to other system using remoting.

In C# code sample

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

    //Close the File Stream
    return ImageData; //return the byte data
Same above code in Vb.Net

Private Function StreamFile(ByVal filename As String) As Byte()
    Dim fs As New FileStream(filename, FileMode.Open, FileAccess.Read)
    ' Create a byte array of file stream length
    Dim ImageData As Byte() = New Byte(fs.Length - 1) {}
    'Read block of bytes from stream into the byte array
    fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length))
    'Close the File Stream
        'return the byte data
    Return ImageData
End Function
Above method accept file path as an input parameter and return you byte array.



Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend