2012-08-01 5 views
5

표준화 된 파일 시스템 보관 프로세스에서 사용할 SSIS 패키지를 작성하려고합니다. 기본적으로 구성 테이블에 정보를 추가 한 다음이 테이블을 사용하여 지정된 폴더의 특정 파일을 보관할 수 있습니다. 내 문제는 많은 파일에 동적 이름이 있으므로 모든 파일의 목록을 가져온 다음 어떤 파일을 만져야하는지 결정해야한다는 것입니다.SSIS 스크립트 작업 파일 이름 가져 오기 및 SSIS 개체 변수 저장

C#/VB 프로그래머가 아니기 때문에 패키지의 일부를 스크립팅 할 때 특정 네트워크 디렉토리에있는 모든 파일을 가져 와서이 파일 이름을 SSIS 객체 변수에 다시 입력 할 때 몇 가지 문제가 발생합니다.

모든 파일을 읽을 폴더의 UNC 위치가 포함될 문자열 변수 'User :: SourceNetworkFolderName'이 있습니다. 그런 다음이 모든 파일 이름 (확장명 포함)을 'User :: SourceFilesInTheDirectory'라는 SSIS 개체 변수로 다시 전달하고 싶습니다. 개체 변수에 파일 이름 목록이 있으면 SQL 테이블로 foreach 루프를 돌릴 것입니다.

누구나 내 변수 디렉토리에서 내 SSIS 개체 변수에 대한 모든 파일 이름 목록을 가져 오는 방법에 대한 구체적인 제안 사항이 있습니까?

미리 감사드립니다.

편집 : 여기 내 업데이트 된 코드 : 스크립트 내부

using System; 
using System.Data; 
using Microsoft.SqlServer.Dts.Runtime; 
using System.Windows.Forms; 
using System.IO; 
using System.Collections.Generic; 
using System.Data.SqlClient; 

namespace ST_f5e4ae71f14d40d8811af21fa2a9a622.csproj 
{ 
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")] 
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase 
    { 

     #region VSTA generated code 
     enum ScriptResults 
     { 
      Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, 
      Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure 
     }; 
     #endregion 

     public void Main() 
     { 
     //Setup Connection String to SQL 
      SqlConnection SQLConnection = new SqlConnection(
             //"user id=username;" +     //UserName 
             //"password=password;" +     //Password 
             "Trusted_Connection=true;" +    //Windows Auth 
             "server=SERVERNAME;" +     //SQL Server 
             "database=DATABASENAME; " +    //SQL Database 
             "connection timeout=30;" +    //connection timeout 
             "Network Library=dbmssocn");    //TCP/IP Connection ("dbnmpntw" = Name Pipes) 


     //Open the SQL Connection and remove the error code 
      try 
      { 
       SQLConnection.Open(); 
      } 
      catch (Exception OpenConnectionError) 
      { 
       Console.WriteLine(OpenConnectionError.ToString()); 
      } 


     //Fetch a list of files from 'SourceNetworkFolderName' SSIS variable to an array called array1. 
      string[] ArrayFileName = Directory.GetFiles(Dts.Variables["SourceNetworkFolderName"].Value.ToString()); 


     //Set up sql variable for table population 
      SqlParameter SQLFileNameParam = new SqlParameter("@FileName", SqlDbType.VarChar, 100); 


     //Loop through the array and insert into an SQL table 
      foreach (string strFileName in ArrayFileName) 
      { 
      //Update sql variable with file names from array 
       SQLFileNameParam.Value = strFileName; 
      //Make the table insert 
       SqlCommand SQLInsertToTable = new SqlCommand("INSERT INTO Archive_Extract_Network_Folder_File_List (FileName) VALUES (@FileName)", SQLConnection); 
      //This snippit allows the use of the variable in the sql script. 
       SQLInsertToTable.Parameters.Add(SQLFileNameParam); 
      //Execute SqlCommand 
       SQLInsertToTable.ExecuteNonQuery(); 
      //Clear the parameters and set the object to null  
       SQLInsertToTable.Parameters.Clear(); 
       SQLInsertToTable = null; 
      } 


     //Close the SQL Connection and remove the error code 
      try 
      { 
       SQLConnection.Close(); 
      } 
      catch (Exception CloseConnectionError) 
      { 
       Console.WriteLine(CloseConnectionError.ToString()); 
      } 


     //Set array to null since it is no longer required. 
      ArrayFileName = null; 


     //Exit on success 
      Dts.TaskResult = (int)ScriptResults.Success; 
     } 
    } 
} 

답변

5

, 단지 파일 이름의 배열을 구축하고 (변수가 쓰기 가능하도록 설정되어 있는지 확인하여 변수에 해당 배열을 설정 스크립팅 작업에서). 변수의 유형이 object 인 경우 후속 작업에서 for 루프를 사용하여 반복 할 수 있으며 원하는대로 파일을 처리 할 수 ​​있습니다. 하나의 스크립트에서만 기적을 다룰 필요는 없습니다.

배열에 소스 디렉토리 아래에있는 모든 파일을 넣어 :

string[] array1 = Directory.GetFiles(Dts.Variables("SourceNetworkFolderName").Value.ToString()); 

배열에 "BIN"의 확장자를 가진 모든 파일을 넣어하기 :

string[] array2 = Directory.GetFiles(Dts.Variables("SourceNetworkFolderName").Value.ToString(), "*.BIN"); 

당신은에 System.IO을 포함해야 스크립팅 코드의 맨.

편집 :

가 반복 작업에 의해 처리를 위해 목록에 배열로 변환합니다. 위의 코드를 호출 한 후,이 전화 :

List<string> fileList = new List<string>(astrTest); 
Dts.Variables["SourceFilesInTheDirectory"].Value = fileList; 

당신은 스크립트 파일의 맨 위에 System.Collections.Generic을 포함해야합니다.

+0

도움 주셔서 감사합니다! 나는 진전을 보였지만 나는 다시 붙어있다. 내 새 문제는 내가 스크립트 작업에서 내 개체 변수를 채우는 방식과 관련이 있다고 생각합니다. 디버거에서 watch를 사용하고 있는데 'User :: SourceFilesInTheDirectory'변수가 표시됩니다. 값이 {Dimensions : [2]} Type = String [] 이 변수를 ADO로 사용하려면 열거자를 읽어야합니다. 값 = {System.Data.DataSet} Type = DataSet – Joe

+0

이 변수를 Foreach ADO Enumerator로 실행하려고하면 디버깅 오류가 발생합니다. Foreach Enumerator로 사용할 수 있도록이 변수를 올바른 형식으로 가져 오는 방법에 대한 아이디어가 있습니까? 나는 아래에있는 내 코드를 붙여 넣은 : – Joe

+0

'코드 배열 문자열로 'SourceNetworkFolderName'SSIS 변수에서 파일 목록을 가져 오기 { // 공공 무효 메인() [] 배열 1 = Directory.GetFiles (Dts.Variables [ "SourceNetworkFolderName"]. Value.ToString()); // 배열의 모든 파일 이름으로 'SourceFilesInTheDirectory'라는 SSIS 개체 변수를 채 웁니다. Dts.Variables [ "SourceFilesInTheDirectory"]. 값 = array1; Dts.TaskResult = (int) ScriptResults.Success; } ' – Joe