2009-12-01 54 views
1

我想從csv文件中將記錄從Silverlight前端導入到數據庫。我正在使用WCF服務來執行數據庫操作。當我傳遞整個文件路徑(硬編碼)時,我能夠向DB添加記錄,但由於Silverlight中的OpenFileDialog不允許獲取文件路徑(由於安全原因),我嘗試使用WCF服務並通過FileInfo屬性或StreamReader然後執行操作。但它給了我一個例外。我有以下的代碼 -從Silverlight的異步調用將StreamReader傳遞給WCF服務

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)傳遞F ileInfo

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()

任何人都可以請幫助我/建議解決方案或更好的方法來從csv導入記錄到數據庫編程使用Silverlight。

謝謝!

回答

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()) 
+0

感謝卡洛斯,這確實給了我一個方向。我工作過,它似乎很好。現在我改變了它的工作方式,我首先將文件上傳到服務器,然後使用它來導入記錄。感謝您提出建議並抱歉遲到回覆。 – Vishal 2009-12-03 18:18:28