简体   繁体   English

SQL Server和C#-如何检查我要上传的varbinary(max)文件是否已存在于表中?

[英]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: 我将文件以以下格式存储在SQL Server的表中:

FileID - int (auto increment), FileName - VarBinary(MAX), FileData - VarBinary(MAX). FileID-int(自动递增),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: 我想做的是-通过上传新的FileName和FileData作为参数,返回FileName和File Data匹配的第一个FileID,如下所示:

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. 我希望不要获取每个文件的数据,并且尽可能使用C#进行比较。

As others already wrote in their comments: First, extend you table to hold 2 more columns. 正如其他人在评论中所写:首先,扩展您的表以容纳另外2列。 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). 然后,查询SQL Server以查找包含相同长度和相同哈希(以及相同名称,如果您希望将具有不同名称的相同文件视为不同文件)的行。 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. 如果命中,则不将文件传输到SQL Server,如果命中,则创建新记录。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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