Monday, August 16, 2010

To insert a file in Database in C#

Reading The File

string filePath = Server.MapPath("APP_DATA/Docu.docx");
string filename = Path.GetFileName(filePath);
FileStream fS = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fS);

Inserting The Data
insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";

SqlCommand cmd = new SqlCommand(strQuery);

cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;

cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/";

cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;

private Boolean InsertUpdateData(SqlCommand cmd)


    String strConnString = System.Configuration.ConfigurationManager


    SqlConnection con = new SqlConnection(strConnString);

    cmd.CommandType = CommandType.Text;

    cmd.Connection = con;





        return true;


    catch (Exception ex)



        return false;