1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
#endregion
namespace ST_084c9ea4e493433cb755fe920dcb2ba1
{
class Program
{
static void Main(string[] args)
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\sqlserver\Archive";
try
{
//Declare Variables and provide values
string SourceFolderPath = @"C:\sqlserver\source\";
string FileExtension = ".txt";
string FileDelimiter = ";";
string TableName = "[dbo].[anis_test]";
string ArchiveFolder = @"C:\sqlserver\Archive";
//Get files from folder
string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
foreach (string fileName in fileEntries)
{
//Create Connection to SQL Server
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "Data Source =SQLEXPRESS;" + " Initial Catalog =tempdb; "
+ "Integrated Security=true;";
int counter = 0;
string line;
string ColumnList = "";
System.IO.StreamReader SourceFile = new System.IO.StreamReader(fileName);
SQLConnection.Open();
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
//By using Header Row, Build Column List
ColumnList = "[" + line.Replace(FileDelimiter, "];[") + "]";
}
else
{
//Build and Execute Insert Statement to insert record
string query = "Insert into " + TableName + " (" + ColumnList + ") ";
query += "VALUES('" + line.Replace(FileDelimiter, "';'") + "')";
SqlCommand SQLCmd = new SqlCommand(query, SQLConnection);
SQLCmd.ExecuteNonQuery();
}
counter++;
}
SourceFile.Close();
SQLConnection.Close();
//move the file to archive folder after adding datetime to it
File.Move(fileName, ArchiveFolder +
(fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "")
+ "_" + datetime + FileExtension);
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
}
}
}
}
} |
Partager