我需要访问作为 Filestream
数据存储在 SQL Server 中的 pdf 文件。我正在开发 .Net Core 2(Razor 页面)应用程序。
我正在尝试访问此页面上概述的 Filestream
数据的方法:
Create Client Applications for FILESTREAM Data
但是,SqlFileStream
类型似乎在 System.Data.SqlTypes
的 .Net Core 2 版本中不可用。
从 SQL Server .Net Core 2 访问 Filestream
数据的最佳方式是什么?
此外,是否有一种方法可以以更“精简”的方式使用 Linq 和 Entity Framework ,而不必通过设置 SqlCommand
来设置“经典”SQL 查询,SqlConnection
等?
最佳答案
这将在 .NET Core 3 中作为 Microsoft.Data.SqlClient 的一部分提供.你可以试试 preview ,但正式版本即将发布。
它之前被追踪到这里:https://github.com/dotnet/SqlClient/issues/15
首先创建您的数据库。可以找到一个很好的例子 here .
安装 SQLClient nuget。
Install-Package Microsoft.Data.SqlClient -Version 1.0.19249.1
请注意 System.Data
不再使用。新的命名空间是 Microsoft.Data
。
这是一个简单的应用程序(来自上面提到的示例):
class Program
{
const string cs =@"Data Source=<your server>;Initial Catalog=MyFsDb;Integrated Security=TRUE";
static void Main(string[] args)
{
Save();
Open();
}
private static void Save()
{
var path = @"C:\Files1\testfile.txt";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader rdr = new BinaryReader(fs);
byte[] fileData = rdr.ReadBytes((int)fs.Length);
rdr.Close();
fs.Close();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
string sql = "INSERT INTO MyFsTable VALUES (@fData, @fName, default)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@fData", SqlDbType.Image, fileData.Length).Value = fileData;
cmd.Parameters.Add("@fName", SqlDbType.NVarChar).Value = "Some Name";
cmd.ExecuteNonQuery();
con.Close();
}
}
private static void Open()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlTransaction txn = con.BeginTransaction();
string sql = "SELECT fData.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT(), fName FROM MyFsTable";
SqlCommand cmd = new SqlCommand(sql, con, txn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string filePath = rdr[0].ToString();
byte[] objContext = (byte[])rdr[1];
SqlFileStream sfs = new SqlFileStream(filePath, objContext, System.IO.FileAccess.Read);
byte[] buffer = new byte[(int)sfs.Length];
sfs.Read(buffer, 0, buffer.Length);
sfs.Close();
string fileContents = System.Text.Encoding.UTF8.GetString(buffer);
Console.WriteLine(fileContents);
}
rdr.Close();
txn.Commit();
con.Close();
}
}
}
关于c# - 在 .Net 核心 2 中使用 SQL Server 文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372491/