Một tập tin docx giống như một file zip đó là bộ sưu tập của một số tập tin. Còn về chuyển đổi thành nhị phân và sau đó lưu vào DB
Something như followswill làm việc
Để lưu
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();
Retrieval là một quá trình phức tạp chút như sau
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();
Xem các bài viết sau để được trợ giúp và chi tiết
Tiết kiệm:
retreival:
Nguồn
2010-02-13 21:16:25
Cảm ơn điều này dường như là một. Tôi sẽ chờ đợi một chút nếu ai đó có một số ý tưởng khác, cách :-) Nếu không tôi sẽ chấp nhận nó như là câu trả lời cuối cùng. – MadBoy
Vui mừng điều này đã giúp –
Bất kỳ ý tưởng nào tại sao quá trình này quá chậm? –