简体   繁体   中英

SQL Server & C# - How can I check if a varbinary(max) file i'm uploading already exists in a table?

I am storing files in a table in SQL Server, in the following format:

FileID - int (auto increment), FileName - VarBinary(MAX), FileData - VarBinary(MAX).

What I would like to do is - by uploading a new FileName & FileData as parameters, return the first FileID where the FileName & File Data match, like so:

SqlCommand cmd = new SqlCommand("SELECT TOP 1 FileID FROM Attachments WHERE FileName = @FileName AND FileData = @FileData", Program.connection);
cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(MyFile));
cmd.Parameters.Add("@FileData", SqlDbType.VarBinary).Value = File.ReadAllBytes(MyFile);
int result = (int)cmd.ExecuteScalar();

However no matter what I do, the function simply terminates (with no exception) when it comes to actually execute the query, on the last line. What am I doing wrong?

I'd prefer not to grab the data for each file & do the comparison in C# if possible.

As others already wrote in their comments: First, extend you table to hold 2 more columns. One for a hash of the contents and one for the filelength. You can then hash the contents of the file when a user uploads it and get it's length. Then you query your SQL-Server to find rows which contain the same length and the same hash (and the same name, if you want the same file with a different name to be considered as a different file). If you get a hit, you don't transfer the file to the SQL-Server, if you don't get a hit, you create a new record.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM