In programming, we often encounter the problem of "saving files to a database," which is no longer a difficult problem, but may be a little difficult for some of the friends who just started programming. In fact, the method is very simple, but probably because these friends just started programming soon, temporarily did not find a way.
Here's a brief introduction to using C # to accomplish this task.
First, I'll introduce you to save the file to the database.
Save the file to the database, in effect, after converting the file into a binary stream, save the binary stream to the corresponding field in the database. The data type for this field in SQL Server is image, which is the OLE object in Access.
Code
[Copy to Clipboard]
CODE:
//save files to SQL Server database
FileInfo fi=new FileInfo (fileName);
FileStream Fs=fi. OpenRead ();
byte[] bytes=new byte[fs. Length];
FS. Read (Bytes,0,convert.toint32 (FS). Length));
SqlCommand cm=new SqlCommand ();
cm. CONNECTION=CN;
Cm.commandtype=commandtype.text;
if (CN. State==0) cn. Open ();
cm.commandtext= "INSERT INTO" +tablename+ "(" +fieldname+ ") VALUES (@file)";
SqlParameter spfile=new SqlParameter ("@file", sqldbtype.image);
spfile.value=bytes;
Cm. Parameters.Add (SpFile);
cm. ExecuteNonQuery ()
//Save files to an Access database
FileInfo fi=new FileInfo (fileName);
FileStream Fs=fi. OpenRead ();
byte[] bytes=new byte[fs. Length];
FS. Read (Bytes,0,convert.toint32 (FS). Length));
OleDbCommand cm=new OleDbCommand ();
cm. CONNECTION=CN;
Cm.commandtype=commandtype.text;
if (CN. State==0) cn. Open ();
cm.commandtext= "INSERT INTO" +tablename+ "(" +fieldname+ ") VALUES (@file)";
oledbparameter spfile=new oledbparameter ("@file", oledbtype.binary);
spfile.value=bytes;
cm. Parameters.Add (SpFile);
cm. ExecuteNonQuery ()
//Save client files to database
sql= "Update t_mail set attachfilename= @attachfilename, attachfile= @attachfile where mailid=" +mailid;
mycommand = new SqlCommand (sql, New SqlConnection (ConnStr));
string path = Fl_name. Postedfile.filename;
string Filename=path. Substring (path. LastIndexOf ("") +1,path. Length-path.lastindexof ("")-1);
myCommand.Parameters.Add ("@attachfilename", SqlDbType.VarChar);
mycommand.parameters["@attachfilename"]. Value=filename;
myCommand.Parameters.Add ("@attachfile", sqldbtype.image);
Stream fileStream = fl_name. Postedfile.inputstream;
int intfilesize = Fl_name. Postedfile.contentlength;
byte[] filecontent = new Byte[intfilesize];
int intstatus = FileStream.Read (filecontent,0,intfilesize); File read to filecontent array
mycommand.parameters["@attachfile"]. Value= ((byte[]) filecontent);
Filestream.close ();
MyCommand.Connection.Open ();
Mycommand.executenonquery ();
MyCommand.Connection.Close ();