views:

933

answers:

1

I'm looking for a very example file upload code snipplet/solution in Silverlight. Having done search I've found numerous controls/projects but all of them were quite complex; supporting multiple file upload, file upload progress, image re-sampling and lots of classes.

I'm looking for the simplest possible scenario with short, clean and easy to understand code.

+4  A: 

This code is pretty short and (hopefully) easy to understand:

private Stream _data;
private string uploadUri;
private void Upload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = "All files (*.*)|*.*";
bool? retVal = dlg.ShowDialog();

if (retVal != null && retVal==true)
{    
    _data = dlg.File.OpenRead();
    UploadFile();
}
}

private void UploadFile()
{
FileStream _data; // The file stream to be read
string uploadUri;

byte[] fileContent = new byte[_data.Length]; // Read the contents of the stream into a byte array
_data.Read(fileContent, 0, _data.Length);

WebClient wc = new WebClient();
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
Uri u = new Uri(uploadUri);
wc.OpenWriteAsync(u, null, fileContent); // Upload the file to the server
}

void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) // The upload completed
{
if (e.Error == null)
{
  // Upload completed without error
}

For a complete downloadable solution see this post: File Upload in Silverlight - a Simple Solution

Gergely Orosz
Thanks for the link!
JohnC
For the benefit of anyone looking at this answer in future, UploadFileAsync or UploadDataAsync would probably be more appropriate here. OpenWriteAsync is great for writing a stream, but it doesn't take a byte array like fileContent as an argument and upload it. OpenWriteCompletedEventHandler means "The steam is now ready for writing" rather than "The upload is complete".
Iain Collins
Thanks for noting, I wasn't aware of UploadFileAsync. I've done a little searching and came across that it wasn't supported in SL2... I'll look into if it's supported in version 3 and update the code accordingly.
Gergely Orosz
Oops sorry Gergley I rashly assumed UploadFileAsync would be in Silverlight because WebClient is! You are right, it seems like it is not, not even in 3.0 http://msdn.microsoft.com/en-us/library/system.net.webclient_members.aspx :-(
Iain Collins