Step 1) Create Silverlight Project with .Web Option
i.e SilverlightApplication and SilverlightApplication.Web
Step 2) Add WCF service to SilverlightApplication.Web
Interface
[ServiceContract]
public interface IService1
{
[OperationContract]
bool uploads(byte[] bytes, String fileName);
}
Implementation
public class Service1 : IService1
{
public bool uploads(byte[] bytes ,String fileName)
{
bool b = !true;
try
{
fileName = @"C:\inetpub\wwwroot\SilverlightApplication.Web\Uploads\"+fileName;
MemoryStream ms = new MemoryStream(bytes);
StreamReader reader = new StreamReader(ms);
System.IO.File.WriteAllText(fileName,reader.ReadToEnd());
b = true;
}
catch (Exception ex)
{
throw ex;
}
return b;
} }
make sure permissions for uploads folder
Leave Web.config settings, because .net 4.0 will take care of it.
Step 3) Run the Service.
in my App:it is http://localhost:3205/Service1.svc
Step 4) Add Service Reference to SilverlightApplication Project, it will create a proxy class.
Step5) in the XAML Add button and Label to grid layout
<Grid x:Name="LayoutRoot" Height="378">
<TextBlock Text="File Uploading in Silverlight using WCF Service" FontSize="16" Foreground="Red" Margin="10,10,-10,332"
>
</TextBlock>
<Button Content="Upload File(s)" HorizontalAlignment="Left" VerticalAlignment="Top" Width="159" x:Name="fileuploadone" Margin="192,106,0,0" Click="fileuploadone_Click" Height="27"/>
<sdk:Label Content="no uploaded files" x:Name="lblfilestats" HorizontalAlignment="Left" Height="123" VerticalAlignment="Top" Width="454" Margin="58,176,0,0"/>
</Grid>
Button handler invokes dialog box to select a file(s).
Label will display Filename uploaded to server using WCF Service.
Step 6) Invoke upload WCF service client in Button Handler.
private void fileuploadone_Click(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog od = new OpenFileDialog();
od.Multiselect = true;
bool? b = od.ShowDialog().GetValueOrDefault(true);
if (b.HasValue)
{
if (b.Value == true)
{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
foreach (FileInfo fi in od.Files)
{
lblfilestats.Content = fi.Name + fi.Length + fi.Extension;
FileStream fs = fi.OpenRead();
byte[] bytes = new byte[fs.Length];
client.uploadsAsync(bytes,fi.Name);
client.uploadsCompleted += client_uploadsCompleted;
}
}
else MessageBox.Show("showdialog returns false");
// od.Files
}
else MessageBox.Show("showdialog returns no value");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void client_uploadsCompleted(object sender, ServiceReference1.uploadsCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
return;
}
if (e.Result)lblupload.Content="Success";
else lblupload.Content="Failed";
}
Step 7) Check Uploads Folder for uploaded files
Tags:file upload in silverlight 5 using wcf C#, fileupload in silverlight, upload multiple files from silverlight, upload files using WCF, client side upload using wcf








