Monday, August 16, 2010

To insert a file in Database in asp.net 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/vnd.ms-word";


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


InsertUpdateData(cmd);
private Boolean InsertUpdateData(SqlCommand cmd)


{


    String strConnString = System.Configuration.ConfigurationManager


    .ConnectionStrings["conString"].ConnectionString;


    SqlConnection con = new SqlConnection(strConnString);


    cmd.CommandType = CommandType.Text;


    cmd.Connection = con;


    try


    {


        con.Open();


        cmd.ExecuteNonQuery();


        return true;


    }


    catch (Exception ex)


    {


        Response.Write(ex.Message);


        return false;


    }


    finally


    {


        con.Close();


        con.Dispose();


    }


}