运行程序后,选择一个文件并上传,如下图所示:

至此,我们就完成了一个使用Web Service上传文件的示例,后面的章节我还会介绍在Silverlight中使用WCF等其它方式上传文件。
2. 使用WCF上传文件
前面我介绍了如何使用Web Service上传文件,同样也可以使用WCF来实现文件上传,我们通过一个示例来说明这一点。首先定义上传文件服务契约,如下代码所示:
C#
[ServiceContract]编写服务实现,在Upload方法里面,实现将文件写入服务器,此处为了演示使用了绝对路径和固定的文件名,在实际开发中大家可以根据实际需要来设置具体文件命名规则以及保存路径,如下代码所示:
public interface IFileService
{
[OperationContract]
void Upload(byte[] FileByte, String FileExtention);
}
public void Upload(byte[] FileByte, String FileExtention)修改配置配置文件,别忘了设置绑定为basicHttpBinding,并添加服务引用。编写一个简单的用户界面,大家可以参考使用Web Service上传文件一节中的代码,这里不再重复,直接编写代码调用WCF服务,如下代码所示:
{
FileStream stream = new FileStream(@"D:\Example." + FileExtention, FileMode.Create);
stream.Write(FileByte, 0, FileByte.Length);
stream.Close();
stream.Dispose();
}
C#
void OnUploadClick(object sender, RoutedEventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == DialogResult.OK)
{
String fileName = openFile.SelectedFile.Name;
FileServiceClient client = new FileServiceClient();
client.UploadCompleted += new EventHandler<AsyncCompletedEventArgs>(OnUploadCompleted);
Stream stream = (Stream)openFile.SelectedFile.OpenRead();
stream.Position = 0;
byte[] buffer = new byte[stream.Length + 1];
stream.Read(buffer, 0, buffer.Length);
String fileExtention = fileName.Substring(fileName.IndexOf('.') + 1);
client.UploadAsync(buffer, fileExtention);
}
}
void OnUploadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
tblStatus.Text = "上传文件成功!";
}
}