2011-03-31 21 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