In this article we will see how file (CSV) is converted into byte Array
In page_load even write the below code, in this we are passing file name which is to be converted to byte array.
string path = “sample.csv”; ReadByteArrayFromFile(Server.MapPath(path); public byte[] ReadByteArrayFromFile(string fileName) { // declare byte array variable byte[] buff = null; // open the file with read access by declaring FileStream object FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); // pass FileStream object to BinaryReader BinaryReader br = new BinaryReader(fs); // get the file length long numBytes = new FileInfo(fileName).Length; // convert binary reader object data to ByteArray, using following statement buff = br.ReadBytes((int)numBytes); // return byte array object return buff; } To test whether byte array conversion happened properly or not do the below modification In page load event string path = “sample” + “.csv”; string path1 = “samplenew1″ + “.csv”; // read byte array from sample.csv & create new file with samplenew1.csv writeByteArrayToFile(ReadByteArrayFromFile(Server.MapPath(path)), Server.MapPath(path1)); Now we will not do any modification to “ReadByteArrayFromFile” function Will define new function call “writeByteArrayToFile” which will take byte array & new file name as parameters. public bool writeByteArrayToFile(byte[] buff, string fileName) { // define bool flag to identify success or failure of operation bool response = false; try { // define filestream object for new filename with readwrite properties FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); // define binary write object from file stream object BinaryWriter bw = new BinaryWriter(fs); // write byte array content using BinaryWriter object bw.Write(buff); // close binary writer object bw.Close(); // set status flag as true response = true; } catch (Exception ex) { Console.WriteLine(ex.Message); // set status as false, if operation fails at any point response = false; } return response; }
Happy Kooding. Hope this helps!!!!!!