您好,我是使用c#(Windows应用程序)进行编程和制作应用程序的新手,希望将pdf或word文件保存在服务器文件夹中,而不是直接保存在数据库中。我可以看到很多解决方案,但没有我的要求。
1,我想将文件文件保存在文件夹中。 2,我想在datagridview中显示保存的文件。 3,我要从datagridview保存的文件中下载和删除文件。 4,我想将文件保存在用代码定义的微粒文件夹中。
我有以下代码。
SqlDataAdapter objAdapter = new SqlDataAdapter(strQuery_AllAttachments_AllFields, objConn);
objAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
SqlCommandBuilder objCmdBuilder = new SqlCommandBuilder(objAdapter);
DataTable objTable = new DataTable();
FileStream objFileStream = new FileStream(strFile, FileMode.Open, FileAccess.Read);
int intLength = Convert.ToInt32(objFileStream.Length);
byte[] objData;
objData = new byte[intLength];
DataRow objRow;
string[] strPath = strFile.Split(Convert.ToChar(@"\"));
objAdapter.Fill(objTable);
objFileStream.Read(objData, 0, intLength);
objFileStream.Close();
objRow = objTable.NewRow();
objRow["FileName"] = strPath[strPath.Length - 1]; //clip the full path - we just want last part!
objRow["FileSize"] = intLength / 1024; // KB instead of bytes
objRow["CustData"] = objData; //our file
objRow["CustName"] = comboBox1.Text.ToString();
objRow["CaseName"] = textBox1.Text.ToString();
objRow["Remarks"] = textBox3.Text.ToString();
objRow["Date"] = dateTimePicker1.Value.ToShortDateString();
objTable.Rows.Add(objRow); //add our new record
objAdapter.Update(objTable);
}
private void btnDownloadFile_Click(object sender, EventArgs e)
{
SaveAttachment(sfdMain, gridViewMain);
FillDataGrid(gridViewMain, strQuery_AllAttachments); // refresh grid
}
private void SaveAttachment(SaveFileDialog objSfd, DataGridView objGrid)
{
string strId = objGrid.SelectedRows[0].Cells["ID"].Value.ToString();
if (!string.IsNullOrEmpty(strId))
{
SqlCommand sqlCmd = new SqlCommand(strQuery_GetAttachmentById, objConn);
sqlCmd.Parameters.AddWithValue("@attachId", strId);
SqlDataAdapter objAdapter = new SqlDataAdapter(sqlCmd);
DataTable objTable = new DataTable();
DataRow objRow;
objAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(objAdapter);
objAdapter.Fill(objTable);
objRow = objTable.Rows[0];
string fileName = Convert.ToString(objGrid.SelectedRows[0].Cells["FileName"].Value.ToString());
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
objSfd.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
objSfd.Title = "Save File as";
objSfd.CheckPathExists = true;
objSfd.FileName = fileName;
byte[] objData;
objData = (byte[])objRow["CustData"];
if (objSfd.ShowDialog() != DialogResult.Cancel)
{
string strFileToSave = objSfd.FileName;
FileStream objFileStream = new FileStream(strFileToSave, FileMode.Create, FileAccess.Write);
objFileStream.Write(objData, 0, objData.Length);
objFileStream.Close();
}
}