Я использую DocX для создания .docx файлов. Вместо того, чтобы хранить их на жестком диске, Доле или SharePoint я предпочел бы хранить их в Базе данных SQL. Таким образом, мои вопросы:
С отношениями,
MadBoy
PS. Я предпочел бы надлежащий код с точки зрения использования Используя старый 'школьный' путь:
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDepozyt))
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
using (var sqlQueryResult = sqlQuery.ExecuteReader())
while (sqlQueryResult != null && sqlQueryResult.Read())
Файл docx подобен zip-файлу, который представляет собой набор из нескольких файлов. Как насчет преобразования в двоичный код и последующего сохранения в БД
Будет работать следующее
Чтобы сохранить
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();
Для получения справки и подробностей см. Следующие статьи
Сохранение :
Восстановление :
Я знаю, что он не использует считыватели, но вот образец, чтобы запросить его и сохранить на диск. Чтобы вернуть его, это будет просто вставка или обновление, передаваемое в байтах []. Тип данных будет varbinary max в sql.
SqlConnection connection = new SqlConnection ("...");
connection.Open ();
SqlCommand command = new
SqlCommand ("select...e", connection);
byte[] buffer = (byte[]) command.ExecuteScalar ();
connection.Close();
FileStream fs = new FileStream(@"C:\test.pdf", FileMode.Create);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
считыватель может выглядеть примерно так
while (myReader.Read())
{
byte[] file = myReader.GetBytes(0));
// might be
file = (byte[])GetValue(0);
}