I have a SQL Server 2008-R2 database that has a table that is storing different types of files (Word Docs, PDF, TIF, etc), I can successfully retrieve these files from the database using the following method:
private void GetFilesFromDatabase() {
try
{
const string connStr = @"Data Source=localhost\SQLInstance;Initial Catalog=MyData;Integrated Security=True;";
//Initialize SQL Server connection.
SqlConnection CN = new SqlConnection(connStr);
//Initialize SQL adapter.
SqlDataAdapter ADAP = new SqlDataAdapter("Select ole_id, ole_object From OLE Where ole_id = 21601", CN);
//Initialize Dataset.
DataSet DS = new DataSet();
//Fill dataset with FilesStore table.
ADAP.Fill(DS, "FilesStore");
//Get File data from dataset row.
byte[] FileData = (byte[])DS.Tables["FilesStore"].Rows[0]["ole_object"];
string FileName = @"C:\Temp\Text.doc";
//Write file data to selected file.
using (FileStream fs = new FileStream(FileName, FileMode.Create))
{
fs.Write(FileData, 0, FileData.Length);
fs.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
This file I am retrieving is a Word Doc file according to other information contained in that particular row. When I attempt to open the file after retrieving it to disk the data all appears to be gibberish and is not able to be read. Now I believe that these files were compressed prior to be saved to the database but I don't know how to de-compress them so that they can be viewed, any thoughts on how I may accomplish this? My ultimate goal is to move these images into another database.
Your code to save files look OK. Assuming your original data was .DOC file and you got bad file after saving you pretty much out of luck. You may want to look at the content of the file in binary editor (i.e. Visual Studio's one) to confirm that file is not something obviously different (text/image....).
You need to ask around how files where stored in the database. There is no way this can be answered remotely as it could be compressed, encrypted, split into chunks or even simply corrupted.