C# winform read write any file to Database
Posted on Monday, December 26, 2016
|
No Comments
Browse File for Save to DB
string fileName=""; object file; string ext=""; private void LoadFile() { OpenFileDialog OpenFileDialog = new OpenFileDialog(); OpenFileDialog.Title = "Open File..."; //OpenFileDialog.Filter = "Binary File (*.bin)|*.bin"; OpenFileDialog.InitialDirectory = @"C:\"; if (OpenFileDialog.ShowDialog() == DialogResult.OK) { byte[] file; using (var stream = new FileStream(OpenFileDialog.FileName, FileMode.Open, FileAccess.Read)) { using (var reader = new BinaryReader(stream)) { file = reader.ReadBytes((int)stream.Length); } } fileName = OpenFileDialog.FileName; file = file; ext = Path.GetExtension(OpenFileDialog.FileName); } }
During Save operation use file object as byte array and save to database.
for easy save use entity framework .
where i have select datatype for sql server is varbinary(MAX).
View File to user
private void ViewDocument(Label lblloc, string fileName) { try { if (file == null) { MessageBox.Show("No file for view"); return; } SaveFileDialog savefile = new SaveFileDialog(); // set a default file name savefile.FileName = fileName + ext; // set filters - this can be done in properties as well savefile.Filter = "All files (*.*)|*.*"; if (savefile.ShowDialog() == DialogResult.OK) { // using (StreamWriter sw = new StreamWriter(savefile.FileName)) // sw.WriteLine("Hello World!"); ByteArrayToFile(savefile.FileName, file as byte[]); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public bool ByteArrayToFile(string _FileName, byte[] _ByteArray) { try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); // Writes a block of bytes to this stream using data from // a byte array. _FileStream.Write(_ByteArray, 0, _ByteArray.Length); // close file stream _FileStream.Close(); return true; } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } // error occured, return false return false; }