If you know the name and location of the file that you want to upload to SQL Server, you can simply use the following code to upload the file to SQL Server. I have hard coded the file location in the example.
string strFileLocation = "c:\Temp\SomePictureFile.jpg";
FileStream fs = new FileStream(strFileLocation, FileMode.Open, FileAccess.Read);
int intContentLength = (int)fs.Length;
Byte[] bytImage = new Byte[intContentLength];
fs.Read(bytImage, 0, intContentLength);
// From previous posts, I'll assume you know what to do with "myConnection" and OpenSQLConnection()
OpenSQLConnection();
SqlCommand cmd = new SqlCommand("INSERT INTO TableName(fldAttachment) VALUES (@Attachment)", myConnection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@Attachment", bytImage));
cmd.ExecuteNonQuery();
CloseSQLConnection();
fs.Close();
// and if you need, delete the file that was just uploaded
File.Delete(FileLocation);
You might wonder how code like this might be useful when you need to know the location of the file you are uploading rather than having the user click on "Browse..." and selecting a file to upload. In one of my future posts (that I'm typing up next), you'll see how we extract email attachments into a temporary folder and upload it to SQL Server. For that, we needed to use a temporary folder and as a result, we would know the name and location of the file to upload.