Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save file in SQL Server database if have file path?

I am building some C# desktop application and I need to save file into database. I have come up with some file chooser which give me correct path of the file. Now I have question how to save that file into database by using its path.

like image 689
eomeroff Avatar asked Jan 23 '10 00:01

eomeroff


People also ask

Can you save file on SQL Server database?

Files can be easily saved in the SQL Server Database Saving it in database makes it easily manageable.

How do I save a file in SQL?

Method 1: SQL Query Analyzer Enter and then execute the SQL statement. In the Save Results dialog box, specify the following settings: Save In: Select a directory in which to save the file. File Name: Type a name for the file.


2 Answers

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).

like image 163
Pedro Avatar answered Sep 21 '22 01:09

Pedro


FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
int numBytes = new FileInfo(fileName).Length;
byte[] buff = br.ReadBytes(numBytes);

Then you upload it to the DB like anything else, I'm assume you are using a varbinary column (BLOB)

like image 24
Paul Creasey Avatar answered Sep 18 '22 01:09

Paul Creasey