How do I insert any file extension into a SQL database? [closed]

2

I have always worked by attaching only images to my BDD tables, I remember converting to MemoryStream and then to Byte and inserting ... But I need to insert any kind of file extension into my database.

    
asked by anonymous 11.12.2014 / 19:54

1 answer

2

Safe way to do what you want:

public static int databaseFilePut(MemoryStream fileToPut) {
    int varID = 0;
    byte[] file = fileToPut.ToArray();
    const string preparedCommand = @"
                INSERT INTO [dbo].[Raporty]
                           ([RaportPlik])
                     VALUES
                           (@File)
                    SELECT [RaportID] FROM [dbo].[Raporty]
        WHERE [RaportID] = SCOPE_IDENTITY()
                ";
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
        sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;

        using (var sqlWriteQuery = sqlWrite.ExecuteReader())
            while (sqlWriteQuery != null && sqlWriteQuery.Read()) {
                varID = sqlWriteQuery["RaportID"] is int ? (int) sqlWriteQuery["RaportID"] : 0;
            }
    }
    return varID;
}

I placed GitHub for future reference a>.

Retired that answer in SO .

You can simplify some things if you do not need all the features but you did not show your specific need.

Just will not take the using and leave the code vulnerable to resource leak.

Note the use of type VarBinary for the SQL Server column.

    
11.12.2014 / 20:05