Know your ISP.

User #109447   794 posts
Whirlpool Enthusiast

I am having trouble trying to save a file to a SQL Server image field using VB.NET 2005. I have tried the following 2 methods from Microsoft:

support.microsoft.com/kb/316887/EN-US

support.microsoft.com/kb/308042

When I step through the code, I don't get any errors, but nothing is saved to the database (the image field remains NULL).

Any help would be appreciated.

posted 2007-Apr-8, 9pm AEST
User #61010   15003 posts
Whirlpool Forums Addict

In MySQL you create a BLOB field, and you simply insert the binary data.

SQL Server shouldn't be too much different.

posted 2007-Apr-8, 10pm AEST
User #116301   1230 posts
Whirlpool Enthusiast

Set the column type in SQL Server to varbinary(MAX).

string commandText = "INSERT INTO [x] (FileData) VALUES (@FileData)";

using(SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection)) {
byte[] imageData = new byte[htmlInputFile.PostedFile.Inpu­ tStream.Length];
htmlInputFile.PostedFile.InputStre­ am.Read(imageData, 0, imageData.Length);
sqlCommand.Parameters.AddWithValue­ ("@FileData", imageData);
// execute the command
}

posted 2007-Apr-8, 11pm AEST
User #109447   794 posts
Whirlpool Enthusiast

The Elite Geek writes...

and you simply insert the binary data.

Thanks ... I'm just having trouble with the "converting the file into binary data" bit.

posted 2007-Apr-8, 11pm AEST
User #109447   794 posts
Whirlpool Enthusiast

alexjcampbell writes...

using(SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection)) {
byte[] imageData = new byte[htmlInputFile.PostedFile.Inpu­ tStream.Length];
htmlInputFile.PostedFile.InputStre­ am.Read(imageData, 0, imageData.Length);
sqlCommand.Parameters.AddWithValue­ ("@FileData", imageData);


Thanks, I was really after some ADO.NET code as I am doing it from a Windows Form, not an ASP.NET page. However I'll try changing the field type to VarBinary(MAX) and see if this works with the Microsoft code.

posted 2007-Apr-8, 11pm AEST
User #116301   1230 posts
Whirlpool Enthusiast

jaffa jnr writes...

I was really after some ADO.NET code as I am doing it from a Windows Form, not an ASP.NET page

ADO.Net is used by both WinForms and ASP.Net. The method of inserting the file into the database is exactly the same, it's just how you retrieve the file that is different.

Just read the file into a byte[] using a stream, and then pass this into the sqlCommand.AddWithValue(string, object) method.

posted 2007-Apr-8, 11pm AEST
Hosted by
WebCentral Australia
Big numbers
975,822 threads
17,201,281 posts
2,008,271 whims sent
3,081 wiki topics
235 ISPs listed
8,129 broadband plans
824 modems & routers
40,569 features filled