I am building a C# desktop application and I need to save a file into a SQL Server database. I have come up with some file chooser which gives me the correct path of the file. How can I save that file into the database using its path?
I am building a C# desktop application and I need to save a file into a SQL Server database. I have come up with some file chooser which gives me the correct path of the file. How can I save that file into the database using its path?
5条答案
按热度按时间mnowg1ta1#
It really depends on the type and size of the file. If it's a text file, then you could use
File.ReadAllText()
to get a string that you can save in your database.If it's not a text file, then you could use
File.ReadAllBytes()
to get the file's binary data, and then save that to your database.Be careful though, databases are not a great way to store heavy files (you'll run into some performance issues).
o8x7eapl2#
Then you upload it to the DB like anything else, I'm assume you are using a varbinary column (BLOB)
jxct1oxe3#
So filestream would be it but since you're using SQL 2K5 you will have to do it the read into memory way; which consumes alot of resources.
First of the column type varchar(max) is your friend this give you ~2Gb of data to play with, which is pretty big for most uses.
Next read the data into a byte array and convert it to a Base64String
And reverse the process to recover
You'll want to dispose of those strings as quickly as possible by setting them to string.empty as soon as you have finished using them!
But if you can, just upgrade to 2008 and use FILESTREAM.
r6l8ljro4#
If you're using SQL Server 2008, you could use FILESTREAM (getting started guide here ). An example of using this functionality from C# is here .
huwehgph5#
You would need the file into a byte array then store this as a blob field in the database possible with the name you wanted to give the file and the file type.
You could just reverse the process for putting the file out again.