Сделал метод, который получает значения файла с БД , сохраняет и запускает
private void OpenFile()
{
cs = cs.LoadFile();
List<FileData> fileDatas = new List<FileData>();
using (SqlConnection conn = new SqlConnection(cs.ToString()))
{
try
{
conn.Open();
int rowindex = postsDataGridView.CurrentCell.RowIndex;
int selectId = Convert.ToInt32(postsDataGridView.Rows[rowindex].Cells[0].Value);
string queryOpen = String.Format("update sta_Messages set \"GetDate\" = CAST(GETDATE() AS BINARY(8)) " +
"where \"id\" = {0} " +
"select \"File_Name\", \"File_Ext\", \"File_Content\" " +
"from sta_Messages where \"id\" = {0}", selectId);
SqlCommand command = new SqlCommand(queryOpen, conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string fileName = reader.GetString(0);
string fileExt = reader.GetString(1);
byte[] fileContent = (byte[])reader.GetValue(2);
FileData fileData = new FileData(fileName, fileExt, fileContent);
fileDatas.Add(fileData);
}
if (fileDatas.Count > 0)
{
using (FileStream fs = new FileStream(fileDatas[0].FileName, FileMode.OpenOrCreate))
{
fs.Write(fileDatas[0].FileContent, 0, fileDatas[0].FileContent.Length);
Process.Start(fileDatas[0].FileName);
}
}
}
catch
{
MessageBox.Show("Ошибка! Выберите файл");
}
}
}
Но открывает файл некорректно
вместо текста. Не пойму, проблема в считывании fileContext'a или где. Спасибо за помощь
private void UploadFile()
{
int selectId = 0;
string filePath;
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
filePath = fileDialog.FileName;
string fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1); //Получаем имя файла
string fileExtension = filePath.Substring(filePath.LastIndexOf('.') + 1); //Получаем расширение файла
//sendMessageTextBox.Text = fileName;
byte[] binaryFile; //Массив для хранения бинарных данных файла
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
binaryFile = new byte[fs.Length];
fs.Read(binaryFile, 0, binaryFile.Length);
}
cs = cs.LoadFile();
using (SqlConnection conn = new SqlConnection(cs.ToString()))
{
try
{
conn.Open();
var table = data.Tables["BTA_USERS"];
string row = table.Rows[0]["Пользоватеь"].ToString();
string rowValue = usersDataGridView.CurrentCell.Value.ToString();
if (row == rowValue)
{
MessageBox.Show("Отправка запрещена!");
return;
}
else
{
using (SqlCommand cmd = new SqlCommand("select * from BTA_USERS", conn))
{
cmd.ExecuteReader();
}
}
conn.Close();
conn.Open();
//Запрос на добавление файла в таблицу
int rowindex = usersDataGridView.CurrentCell.RowIndex;
selectId = Convert.ToInt32(usersDataGridView.Rows[rowindex].Cells[1].Value);
string querryUpload = "insert into sta_Messages(\"SetUser_id\", \"GetUser_id\", \"File_Name\", \"File_Ext\", \"File_Content\", \"SetDate\")" +
"values(" + Convert.ToInt32(cs.LastId) + ", '" + selectId + "', '" + fileName + "','" + fileExtension + "','" + binaryFile + "', " + "CAST(GETDATE() AS BINARY(8))" + ")";
using (SqlCommand cmdAddMess = new SqlCommand(querryUpload, conn))
{
try
{
SqlDataReader rezultAddMess = cmdAddMess.ExecuteReader();
if (!rezultAddMess.HasRows && !string.IsNullOrEmpty(sendMessageTextBox.Text)) //Проверка на отправку сообщения
MessageBox.Show("Файл отправлено!");
else
MessageBox.Show("Ошибка!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
GetData();
}
catch
{
MessageBox.Show("Выберите получателя!");
}
}
}
public ConnectionString LoadFile()
{
try
{
ConnectionString result;
XmlSerializer formatter = new XmlSerializer(typeof(ConnectionString));
using (var fs = new FileStream(GetFileXML(), FileMode.Open))
{
result = (ConnectionString)formatter.Deserialize(fs);
}
return result;
}
catch
{
throw new Exception("Ошибка");
}
}
File.ReadAllText(...)