Skip to content

Instantly share code, notes, and snippets.

@zhangzixuan1997
Last active September 14, 2022 01:26
Show Gist options
  • Save zhangzixuan1997/e850c1fc904b470769a9e578cdaab537 to your computer and use it in GitHub Desktop.
Save zhangzixuan1997/e850c1fc904b470769a9e578cdaab537 to your computer and use it in GitHub Desktop.
public void Main()
{
try
{
string FilePath = Dts.Variables["User::Filepath"].Value.ToString();
string TableName = Dts.Variables["User::TableName"].Value.ToString();
//Create an arrary so all files in the folder can be imported.
string[] fileEntries = Directory.GetFiles(FilePath, "*");
//Create an INT var to store line number if file. For loop used to ignore the header.
Int32 ct= 0;
string Line = string.Empty;
string query = string.Empty;
SqlConnection conn = new SqlConnection();
//Double check your rename of the connection if error thrown.
conn = (SqlConnection)(Dts.Connections["DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
foreach (string fileName in fileEntries)
{
System.IO.StreamReader SourceFile = new System.IO.StreamReader(fileName);
ct = 0;
while ((Line = SourceFile.ReadLine()) != null)
{
if (ct != 0)//Ignore the header
{
Line = Line.Trim();
//CSV or text with comma delimted.
query = "Insert into SEANTEST.dbo." + TableName + " values('" + Line.Replace(",", "','"). + "')";
SqlCommand SQLCommand = new SqlCommand(query, conn);
SQLCommand.ExecuteNonQuery();
}
ct++;
}
}
Dts.TaskResult = (int)ScriptResults.Success;
conn.Close();
}
catch (Exception ex)
{
Dts.Events.FireError(0, "Exception-Script Task", ex.Message + ": " + ex.StackTrace, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
enum ScriptResults
{
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment