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

后端 未结 5 2272
生来不讨喜
生来不讨喜 2020-12-15 00:16

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 que

5条回答
  •  长情又很酷
    2020-12-15 01:10

    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.

提交回复
热议问题