How can I save a file in a SQL Server database if have its file path?

8fq7wneg  于 2023-06-04  发布在  SQL Server
关注(0)|答案(5)|浏览(225)

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?

mnowg1ta

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

o8x7eapl

o8x7eapl2#

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)

jxct1oxe

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

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.

r6l8ljro

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 .

huwehgph

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.

相关问题