Overview
We know that the Silverlight 2 provides a rich network communication API, including support for SOAP services, rest services, HTTP based communications, socket communications, and more. In this article, I'll show you how to apply a Web service to file uploads and e-mail messages in Silverlight 2 with a few examples.
Uploading files using Web service
I'll show you how to use Web service to upload files to a server, create a Silverlight project first, and add a asp.net Web service file to your Web test project. Now to implement the related WebMethod, in this method, you will receive two parameters: byte array and file name extension, and create the file on the server as shown in the following code:
public class FileService : WebService
{
[WebMethod]
public int UploadFile(byte[] FileByte, String FileExtention)
{
FileStream stream = new FileStream(String.Format(@"D:\example.{0}", FileExtention),FileMode.CreateNew);
stream.Write(FileByte, 0, FileByte.Length);
stream.Close();
return FileByte.Length;
}
}
To add a simple interface for the user to select a local file, we will call the Web Service in the button click event, as shown in the following code:
<Canvas Background="#FF333333">
<TextBox x:Name="txtFile" Height="30" Width="300" Canvas.Top="120"
Canvas.Left="30" Style="{StaticResource textBoxStyle}"></TextBox>
<Button x:Name="btnUpload" Width="60" Content="上 传" Height="30"
Canvas.Left="340" Canvas.Top="120" Style="{StaticResource buttonStyle}"
Click="OnUploadClick"></Button>
<TextBlock x:Name="tblStatus" Canvas.Left="30" Canvas.Top="160"
FontSize="14" Foreground="White" Text=""></TextBlock>
</Canvas>