C# 将文档文件插入SQL Server中的列中

C# 将文档文件插入SQL Server中的列中,c#,asp.net,sql-server,sql-server-2008,C#,Asp.net,Sql Server,Sql Server 2008,我想在SQL Server中的字段中保存一个文档文件。该文档文件可以包含文本、图表、表格和图片 我想将此文件保存在一个字段中,只要我愿意,我就可以在这些文档文件中搜索并找到我的搜索标题 如何执行此操作?在表中创建一列数据类型varbinary(max),然后重试- string filePath = FileUpload1.PostedFile.FileName; string filename = Path.GetFileName(filePath); string ext = Path.

我想在SQL Server中的字段中保存一个文档文件。该文档文件可以包含文本、图表、表格和图片

我想将此文件保存在一个字段中,只要我愿意,我就可以在这些文档文件中搜索并找到我的搜索标题


如何执行此操作?

在表中创建一列数据类型
varbinary(max)
,然后重试-

string filePath = FileUpload1.PostedFile.FileName;  
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
 switch(ext)
{
    case ".doc":
        contenttype = "application/vnd.ms-word";
        break;
    case ".docx":
        contenttype = "application/vnd.ms-word";
        break;
}
 if (contenttype != String.Empty)
{

    Stream fs = FileUpload1.PostedFile.InputStream;
    BinaryReader br = new BinaryReader(fs);
    Byte[] bytes = br.ReadBytes((Int32)fs.Length);

    //insert the file into database
    string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
       " values (@Name, @ContentType, @Data)";
    SqlCommand cmd = new SqlCommand(strQuery);
    cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
    cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value
      = contenttype;
    cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
    InsertUpdateData(cmd);
    lblMessage.ForeColor = System.Drawing.Color.Green;  
    lblMessage.Text = "File Uploaded Successfully";
}

您可以在SQL中创建一个新的db字段,类型为
VARBINARY(MAX)
,它可以保存任何数据。为了将文档文件保存到其中,我将用一个例子来帮助您

        // Read the file and convert it to Byte Array

        string filePath = FileUpload1.PostedFile.FileName;  
        string filename = Path.GetFileName(filePath);

        Stream fs = FileUpload1.PostedFile.InputStream;

        BinaryReader br = new BinaryReader(fs);

        Byte[] bytes = br.ReadBytes((Int32)fs.Length);



        //insert the file into database

        string strQuery = "insert into tblFiles(Name, Data)" +

           " values (@Name, @Data)";

        SqlCommand cmd = new SqlCommand(strQuery);

        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;



        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;

        InsertUpdateData(cmd);

        lblMessage.ForeColor = System.Drawing.Color.Green;  

        lblMessage.Text = "File Uploaded Successfully";
这里,字段
DATA
在SQL中定义为
VarBinary(max)

关于第二个要求,要在文档中搜索文本,请参考

谢谢我的朋友们 但我希望能够在我的文档文件中搜索。 文档文件可以包含表格,表格可以包含任何类型的数据,如文本、数字和…
图表和图片也可以像表格一样。
我不想将我的文档路径保存在字段中,任何时候我需要先搜索,然后打开文件再搜索。

我想将该文档文件保存到一个字段中并在该字段中搜索

您是否查看了
filestream
功能?我认为当试图在mssql中存储文档时,这种方法是有意义的。利用sql的管理功能实现文件存储的好处。还有一个C#您的意思是如何搜索保存为数据库字节数组的文档文件的内容?