Had to add an attachment functionality to the project I am currently working on at work.
The snippets below use a simple web service (which I didn’t include) that saves the files uploaded to a database and returns the columns read.
You need at least three columns in the table: ID (PK, int), FILENAME (varchar) and CONTENT (BLOB).
// Attach this method to an upload button.
private void UploadFile(object sender, RoutedEventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
// In case you want filtering.
fileDialog.DefaultExt = ".txt";
fileDialog.Filter = "Text documents (.txt)|*.txt";
bool? result = fileDialog.ShowDialog();
if (result == true)
{
using (FileStream fs = new FileStream(fileDialog.FileName, FileMode.Open, FileAccess.Read))
{
Byte[] b = new Byte[fs.Length];
fs.Read(b, 0, b.Length);
fs.Close();
try
{
// Save the byte array (b) to the BLOB column in the database.
// I am using a web service.
WebService.SaveAttachment(Path.GetFileName(fileDialog.FileName), b);
MessageBox.Show("File uploaded!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
// Attach this method to a button (or DataGridRow or whatever) to open the file.
// I am passing in a file ID and I fetch the attachment information from the database.
private void OpenFile(int fileid)
{
var att = WebService.GetAttachment(fileid);
var tempfile = Path.Combine(Path.GetTempPath(), att.Filename);
if (File.Exists(tempfile))
{
File.Delete(tempfile);
}
FileStream create = File.OpenWrite(tempfile);
create.Write(att.Bytes, 0, att.Bytes.Length);
create.Close();
// Opens the file as a new process, not blocking the GUI.
Task.Factory.StartNew(new Action(delegate()
{
Process p = Process.Start(tempfile);
while (p != null && !p.HasExited)
{
Thread.Sleep(100);
}
File.Delete(tempfile);
}));
}
// Attach this method to a download button.
// Again, passing in a file ID.
private void DownloadFile(int fileid)
{
var att = WebService.GetAttachment(fileid);
var saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = att.Filename;
bool? result = saveFileDialog.ShowDialog();
if (result == true)
{
var filename = saveFileDialog.FileName;
using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
// att.Bytes is the BLOB column from the database.
fileStream.Write(att.Bytes, 0, att.Bytes.Length);
MessageBox.Show("File downloaded!");
}
}
}
Reference:
http://support.microsoft.com/en-nz/kb/317016