eomeroff
eomeroff

Reputation: 9915

How can I save a file in a SQL Server database if have its file 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?

Upvotes: 9

Views: 41822

Answers (5)

Pedro
Pedro

Reputation: 133

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

Upvotes: 10

user220583
user220583

Reputation:

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

FileInfo _fileInfo = new FileInfo(openFileDialog1.FileName);
                if (_fileInfo.Length < 2147483647) //2147483647 - is the max size of the data 1.9gb
                {
                    byte[] _fileData = new byte[_fileInfo.Length];
                    _fileInfo.OpenRead().Read(_fileData, 0, (int)_fileInfo.Length);
                    string _data = Convert.ToBase64String(_fileData);
                }
                else
                {
                    MessageBox.Show("File is too large for database.");
                }

And reverse the process to recover

byte[] _fileData  = Convert.FromBase64String(_data);

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.

Upvotes: 2

AdaTheDev
AdaTheDev

Reputation: 147224

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.

Upvotes: 1

Paul Creasey
Paul Creasey

Reputation: 28824

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)

Upvotes: 5

Burt
Burt

Reputation: 7758

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.

Upvotes: 0

Related Questions