使用FILESTREAM(文件流)写入数据
在这个例子中,假设用户产生了一些输入,要将这些输入内容转换成字节数组,并将其存储在Product表的Picture列中,接下来创建一个Visual C#视窗应用程序,命名为FileStreamExample,在新项目的默认表单上,添加一个按钮,命名为btnWriteFile,一个名叫txtInput的文本输入框(TextBox),一个命名为lstResults的列表框(ListBox),然后,在按钮上双击创建一个click事件处理器,包括清单1中的代码。
清单1 使用FILESTREAM存储数据
private void btnWriteFile_Click(object sender, EventArgs e) { string connectionString = ConfigurationManager.ConnectionStrings ["fileStreamDB"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; //Get the PathName of the File from the database command.CommandText = "SELECT Picture.PathName(), " + "GET_FILESTREAM_TRANSACTION_CONTEXT() FROM Product " + "WHERE ProductID = 1"; SqlTransaction transaction = connection.BeginTransaction (IsolationLevel.ReadCommitted); command.Transaction = transaction; using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string path = reader.GetString(0); SqlFileStream stream = new SqlFileStream(path, (byte[])reader.GetValue(1), FileAccess.Write, FileOptions.SequentialScan, 0); string contents = txtInput.Text; stream.Write((System.Text.Encoding.ASCII.GetBytes(contents)), 0, contents.Length); stream.Close(); } } transaction.Commit(); } MessageBox.Show("File contents successfully written"); }
它从app.config使用ConfigurationManager.ConnectionStrings属性检索连接字符串:
string connectionString = ConfigurationManager.ConnectionStrings |