一個的docx文件就像是一個zip文件是幾個文件的集合。怎麼樣轉換成二進制文件,然後保存到數據庫
東西作爲followswill工作
爲了節省
string filePath = "";
string connectionString = "";
FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream);
byte[] file = reader.ReadBytes((int)stream.Length);
reader.Close();
stream.Close();
SqlCommand command;
SqlConnection connection = new SqlConnection(connectionString);
command = new SqlCommand("INSERT INTO FileTable (File) Values(@File)", connection);
command.Parameters.Add("@File", SqlDbType.Binary, file.Length).Value = file;
connection.Open();
command.ExecuteNonQuery();
檢索是有點複雜的過程如下
SqlConnection connection = new SqlConnection("");
string query =
@" SELECT File FROM FileTable where FileID =" + 125;
SqlCommand command = new SqlCommand(query, connection);
FileStream stream;
BinaryWriter writer;
int bufferSize = 100;
byte[] outByte = new byte[bufferSize];
long retval;
long startIndex = 0;
string pubID = "";
connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.Default);
while (reader.Read())
{
pubID = reader.GetString(0);
stream =
new FileStream("abc.docx", FileMode.OpenOrCreate, FileAccess.Write);
writer = new BinaryWriter(stream);
startIndex = 0;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
while (retval == bufferSize)
{
writer.Write(outByte);
writer.Flush();
startIndex += bufferSize;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
}
writer.Write(outByte, 0, (int)retval - 1);
writer.Flush();
writer.Close();
stream.Close();
} reader.Close();
connection.Close();
請看以下文章以獲取幫助和詳細信息
保存:
Retreival:
感謝這似乎是一個。如果別人有更多的想法,我會稍微等一下:-)如果不是,我會接受它作爲最終答案。 – MadBoy 2010-02-14 18:52:06
很高興幫助 – 2010-02-14 19:28:02
任何想法爲什麼這個過程如此緩慢? – 2012-04-24 19:54:29