使用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 |
连接字符串存储在app.config中,如下:
<?xml version="1.0" encoding="utf-8" ?> |
接下来它打开一个到数据库的连接,为SqlCommand对象分配属性值,然后以ProductID=1为条件检索Products表:
command.Connection = connection; |
这个SQL语句使用了新的函数GET_FILESTREAM_TRANSACTION_CONTEXT ()检索当前运行的会话事务,你可以绑定FILESTREAM文件流)文件系统操作到该事务上,但这个事务必须是已经启动了的,并且也不能被异常终止或提交,当没有明确启动的事务可用的,它返回NULL值。
因此,下面的代码调用SqlConnection.BeginTransaction()方法创建一个新的SqlTransaction对象,并将其分配给SqlCommand对象:
SqlTransaction transaction = |
至此,清单1启动ExecuteReader()方法执行SQL语句,执行完查询后,返回文件流的路径,并向它分配一个本地变量:
string path = reader.GetString(0); |
你需要一个流写入到文件中,因此,接下来要创建一个SqlFileStream类的实例,提供路径、事务上下文、文件访问目录、文件选项一览表和分配大小:
SqlFileStream stream = new SqlFileStream(path, |
SqlFileStream类是一个新类SQL Server 2008中才引入的),它提供了以字节序列方式访问FILESTREAM文件流)列的方法,表1对SqlFileStream类暴露在外的属性做了一个简单的描述。
表1 SqlFileStream类属性
接下来清单1开始检索用户的输入,转换成字节数组,然后写入到文件流中:
string contents = txtInput.Text; |
最后,清单1调用SqlTransaction.Commit()方法提交事务:
transaction.Commit(); |
以上就是往由数据库管理的启用了FILESTREAM文件流)特性的文件的基本过程,既然已经知道如何写入FILESTREAM列,那从FILESTREAM列读取就简单了。