111,092
社区成员




//插入文件内容到数据库
static void StoreFile(string filename)
{
//创建一个数据库连接到本地的FileStore 数据库,你可以修改数据库名称
SqlConnection connection = new SqlConnection
("Server=(local) ; Initial Catalog = FileStore ; Integrated Security = SSPI");
//创建一个执行插入命令的SqlCommand对象
SqlCommand command = new SqlCommand
("INSERT INTO MyFiles VALUES (@Filename, @Data)", connection);
//给sql命令的参数赋值
command.Parameters.AddWithValue("@Filename", Path.GetFileName(filename));
//使用File.ReadAllByte方法读取文件内容
command.Parameters.AddWithValue("@Data", File.ReadAllBytes(filename));
//打开连接
connection.Open();
//执行命令
command.ExecuteNonQuery();
//关闭连接
connection.Close();
}
//从数据库读取文件内容
static byte[] RetrieveFile(string filename)
{
SqlConnection connection = new SqlConnection
("Server=(local) ; Initial Catalog = FileStore ; Integrated Security = SSPI");
SqlCommand command = new SqlCommand
("SELECT * FROM MyFiles WHERE Filename=@Filename", connection);
command.Parameters.AddWithValue("@Filename", filename);
connection.Open();
SqlDataReader reader =
command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);//指定顺序读取文件的字节
reader.Read();
MemoryStream memory = new MemoryStream();
long startIndex = 0;
const int ChunkSize = 256;
while (true)
{
byte[] buffer = new byte[ChunkSize];
long retrievedBytes = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize);
memory.Write(buffer, 0, (int)retrievedBytes);
startIndex += retrievedBytes;
if (retrievedBytes != ChunkSize)
break;
}
connection.Close();
byte[] data = memory.ToArray();
memory.Dispose();
return data;
}
static void StoreFile(string filename)
{
SqlConnection connection = new SqlConnection
("Server=(local) ; Initial Catalog = FileStore ; Integrated Security = SSPI");
SqlCommand command = new SqlCommand
("INSERT INTO MyFiles VALUES (@Filename, @Data)", connection);
command.Parameters.AddWithValue("@Filename", Path.GetFileName(filename));
command.Parameters.AddWithValue("@Data", File.ReadAllBytes(filename));
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}