Monday, November 2, 2009

Converting any File to Byte[] and Byte[] to File.

Below C# code takes filepath, where file located as input parameter and gives byte array of that file.

public byte[] ReadFile(string sPath)
{
FileStream fStream = null;
try
{byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
using (fStream)
{
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
}
return data;
}
catch { throw; }
finally { fStream.Dispose(); }
}


Below code snippets takes Byte array and File extention as input parameter and stores the file in application path under temp folder.

public byte[] ReadFile(string sPath)
{
FileStream fStream = null;
try
{byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
using (fStream)
{
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
}
return data;
}
catch { throw; }
finally { fStream.Dispose(); }
}

No comments:

Post a Comment