2011-03-31 18 views
2

嗨我需要從具有表單身份驗證的站點下載文件,並使用Integration Services進一步處理文本文件。關於SSIS腳本組件的WATIN - 單線程公寓

對於文件下載我選擇使用華廷,於是我進口華廷庫和腳本的瀏覽器的步驟。但是,當我嘗試運行代碼時,我收到了帶有此消息的異常。

The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer.

這一切使用 (與方法屬性)

如果我嘗試使用下面這行代碼將其設置爲STA

System.Threading.Thread.CurrentThread.SetApartmentState(Threading.ApartmentState.STA) 

我得到這個例外

Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Failed to set the specified COM apartment state. at System.Threading.Thread.SetApartmentState(ApartmentState state)

如何更改SSIS腳本任務以使用此單線程單元?

回答

2

我已經通過與STA ApartmentState創建另一個線程來解決此問題。

的代碼是這樣的:

Private threadDelegate As ParameterizedThreadStart 
Private filesdir As String 

<STAThread()> _ 
Public Sub Main() 
    Try 
     threadDelegate = New ParameterizedThreadStart(AddressOf Me.DoSomething) 
     StartBrowserRoutine(threadDelegate) 
     Dts.TaskResult = ScriptResults.Success 
    Catch 
     Dts.TaskResult = ScriptResults.Failure 
    End Try 
End Sub 

Private Sub StartBrowserRoutine(ByVal threadRoutine As ParameterizedThreadStart) 
    Dim dialogThread As Thread = New Thread(threadRoutine) 
    dialogThread.TrySetApartmentState(ApartmentState.STA) 
    dialogThread.Start(Nothing) 
    dialogThread.Join(System.Threading.Timeout.Infinite) 
End Sub 

Private Sub DoSomething() 
    'Do Something 
End Sub 

希望這可以幫助別人同樣的問題。

1

我發現你的解決方案,我的情況是類似的非常有用的,我加我,以防有人使用的C#代碼需要它

public void Main() { 
    Thread thread = new Thread(new ParameterizedThreadStart(DoMethod)); 
    thread.SetApartmentState(ApartmentState.STA); 
    thread.Start(); 
    thread.Join(); // wait for thread to end 

    Dts.TaskResult = (int)ScriptResults.Success; 
} 

public void DoMethod(object sender) { 
    System.Windows.Forms.Application.Run(new BrowserWindow("http://x.xxx")); 
} 

這裏是BrowserWindow

class BrowserWindow : Form 
{ 
    private string url; 

    public BrowserWindow(string url) { 
     this.url = url; 
     ShowInTaskbar = false; 
     WindowState = FormWindowState.Minimized; 
     Load += new EventHandler(Window_Load); 
    } 

    void Window_Load(object sender, EventArgs e) { 
     WebBrowser wb = new WebBrowser(); 
     wb.AllowNavigation = true; 
     wb.DocumentCompleted += wb_DocumentCompleted; 
     wb.Navigate(this.url); 
    } 

    void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
    { 
     WebBrowser web = sender as WebBrowser; 
     // here goes the business logic 
    } 
} 
+0

很大,當我這樣做時,沒有可能在SSIS上使用C#,謝謝! – 2015-07-31 20:36:22