从Silverlight的异步调用将StreamReader传递给WCF服务

时间:2009-12-01 18:43:10

标签: wcf silverlight streamreader fileinfo

我想将来自csv文件的记录从Silverlight前端导入到DB。我正在使用WCF服务来执行数据库操作。当我传递整个文件路径(硬编码)时,我能够向DB添加记录,但由于Silverlight中的OpenFileDialog不允许获取文件路径(由于安全原因),我尝试使用WCF服务并通过FileInfo属性或StreamReader然后执行操作。但它给了我一个例外。我有以下代码 -

1)传递StreamReader Page.xaml.vb文件

Dim service As New ServiceReference1.Service1Client
dlg.ShowDialog()
Dim Reader As System.IO.StreamReader
If dlg.File IsNot Nothing Then
   Reader = dlg.File.OpenText
End If
service.ImportPersonInfoAsync(Reader)

'Service1.svc.vb文件

<OperationContract()> _
    Public Sub ImportPersonInfo(ByVal Reader As System.IO.StreamReader)
    'Code to add records to DB table
    End Sub

我收到异常 - 远程服务器返回错误:NotFound(在EndInvoke方法中)

Public Sub EndImportPersonInfo(ByVal result As System.IAsyncResult) Implements ServiceReference1.Service1.EndImportPersonInfo
    Dim _args((0) - 1) As Object
    MyBase.EndInvoke("ImportPersonInfo", _args, result)
End Sub

2)传递FileInfo

Page.xaml.vb文件

If dlg.File IsNot Nothing Then
   ImportFile = dlg.File
End If
service.ImportPersonInfoAsync(ImportFile)

Service1.svc.vb文件

Public Sub ImportPersonInfo(ByVal ImportFile As System.IO.FileInfo)
    Dim Reader As System.IO.StreamReader = ImportFile.OpenText
    'Do operation
End Sub

我在BeginInvoke方法中遇到异常 - 尝试访问该方法失败:System.IO.FileSystemInfo.get_Attributes()

任何人都可以帮助我/建议解决方案或更好的方法,使用Silverlight将记录从csv导入DB程序。

谢谢!

1 个答案:

答案 0 :(得分:0)

FileInfo和StreamReader都不是可序列化的类,因此您无法将它们直接传递给使用WCF的服务器。一个选项是读取内存中的文件,然后将其传递给服务,如下所示。另一个选项是读取多行(List)中的.csv文件并将其传递给服务。

Dim service As New ServiceReference1.Service1
Clientdlg.ShowDialog()
Dim ms As System.IO.MemoryStream
If dlg.File IsNot Nothing Then
   Dim TheFile as Stream = dlg.File.OpenRead()
   Dim Buffer as Byte() = New Byte(10000) { }
   Dim BytesRead as Integer
   Do
      BytesRead = TheFile.Read(Buffer, 0, Buffer.Length)
      ms.Write(Buffer, 0, BytesRead)
   Loop While (BytesRead > 0)
End If
TextEnd Ifservice.ImportPersonInfoAsync(ms.ToArray())
相关问题