I am trying to save a file into a SQL Server database and the column that the file will be saved in is of datatype VARBINARY.
The way I am currently doing this is by getting the file path and turning the file into a byte array.
string SelectedFilePath = "" ;
OpenFileDialog choofdlog = new OpenFileDialog();
if (choofdlog.ShowDialog() == DialogResult.OK)
{
SelectedFilePath = choofdlog.FileName;
}
byte[] Filebytes = File.ReadAllBytes(SelectedFilePath);
Then, I insert the bytes into the database using an insert query and the convert function to convert the byte[] to varbinary:
INSERT * INTO TblFile([FILEID], [FILEDATA])
VALUES('" + Guid.newGuid + "', CONVERT(VARBINARY, '" + Filebytes + "'));
However, in the SQL Server database, the value of the FILEDATA is always
0x53797374656D2E427974655B5D
And it doesn't matter which file I select the FILEDATA will always be that number. So if you could tell me why this is happening and what I should do to prevent it I would very much appreciate that.
byte[] Filebytes = ...(SelectedFilePath)is outside of theifblock. Thus, itsSelectedFilePathdefault value may mess up your logic: i.e. always reading the same file and write it again and again and again to the SQL database. You may want to consider to terminate the operation ifDialogResultisn'tOK.