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