2011-06-06 17 views
2

目前,我有一個SSIS包的腳本任務內硬編碼的文件路徑值。如何在腳本任務中使用包變量?

我有一個字符串變量sPath。我應該如何在Script Task中使用這個變量sPath?

string strPath = "C:\\File.xls"; 
if(File.Exists(strPath)) 
{ 
    File.Delete(strPath); 
} 

回答

7

以下是在Script Task中使用變量的一種可能方式。假設你有一個變量名爲FilePath在你的軟件包上聲明,如截圖#所示,那麼你可以使用下面的代碼來使用Script Task中的變量。這是使用變量的可能方法之一。這裏該變量僅用於使用方法LockForRead讀取該值。如果使用LockForWrite方法聲明變量,則也可以將值寫入變量。

順便說一下,Scrip Task代碼中描述的功能也可以使用SSIS Control Flow任務列表中提供的File System Task執行。

希望有所幫助。

腳本任務內使用包變量:

C#代碼只能在SSIS 2008 and above使用。 。

public void Main() 
{ 
    Variables varCollection = null; 
    string FilePath = string.Empty; 

    Dts.VariableDispenser.LockForRead("User::FilePath"); 
    Dts.VariableDispenser.GetVariables(ref varCollection); 

    FilePath = varCollection["User::FilePath"].Value.ToString(); 

    if (File.Exists(FilePath)) 
    { 
     File.Delete(FilePath); 
    } 

    varCollection.Unlock(); 

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

截圖#1:

1

+0

這就是完美的答案!謝謝 – goofyui 2011-06-06 18:29:50

+0

不知道爲什麼這不被接受。 非常有幫助,謝謝。 – rpcutts 2012-04-05 10:10:11

+0

我們應該在編譯器的'using'語句中包含哪些名稱空間來解決'Variables'聲明? 我不得不用'IDTSVa​​riables100'替換'Variables',並且在調用'GetVariables'方法時用'out'代替'ref'修飾符。 – Zarepheth 2012-07-30 18:00:41