Friday, 8 November 2019

Windows service using C# - append header to csv file


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Configuration;
using System.Timers;

namespace FileHeaderService
{
    public partial class FileHeaderService: ServiceBase
    {
        Timer timer = new Timer();

        public FileHeaderService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            string delayTimer = ConfigurationManager.AppSettings["timerDelay"];
            this.CreateLog("ServiceStart");
            this.AddHeader();

            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = Convert.ToDouble(delayTimer); //number in milisecinds
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            this.CreateLog("ServiceStopped");
        }

        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            AddMetrixHeader();
        }

        protected void AddHeader()
        {
            string sourceFile = ConfigurationManager.AppSettings["sourceFilePath"];
            string targetFile = ConfigurationManager.AppSettings["targetFilePath"];
            string headerFile = ConfigurationManager.AppSettings["headerFilePath"];
            string archiveFile = ConfigurationManager.AppSettings["archiveFilePath"];

            string csvContent = string.Empty;
            string reason = string.Empty;
            string reason2 = "OneFile";
            string[] sourceFileInfo;
            int cnt = Directory.GetFiles(sourceFile).Length;

            if (cnt == 0)
            {
                reason = "NoFile";
                this.CreateLog(reason);
            }

            else
            {             
                sourceFileInfo = Directory.GetFiles(sourceFile, "*.csv", SearchOption.TopDirectoryOnly);
                Boolean firstFile = true;
                foreach (string txtName in Directory.GetFiles(sourceFile, "*.csv"))
                {
                    if (firstFile == true) //process 1 file at a time
                    {
                        string sourceFileName = Path.GetFileName(txtName);
                        sourceFile = sourceFile + sourceFileName;
                        targetFile = targetFile + Path.GetFileNameWithoutExtension(txtName) + System.DateTime.UtcNow.ToString("-MMddyy-hhmmss") + ".csv";

                        StreamReader rd = new StreamReader(headerFile, true);
                        csvContent = rd.ReadToEnd();
                        rd.Close();

                        rd = new StreamReader(sourceFile, true);
                        csvContent = csvContent.ToString() + "\n" + rd.ReadToEnd();
                        rd.Close();

                        StreamWriter wr = new StreamWriter(targetFile, false);
                        StringBuilder sb = new StringBuilder(csvContent);
                        wr.Write(sb.ToString());
                        sb.Clear();
                        wr.Close();

                        //first, delete target archive file if exists, as File.Move() does not support overwrite
                        archiveFile = archiveFile + sourceFileName;
                        if (File.Exists(archiveFile))
                        {
                            File.Delete(archiveFile);
                        }
                        File.Move(sourceFile, archiveFile);

                        firstFile = false;
                        reason = "Success";
                        this.CreateLog(reason, sourceFileName, targetFile);
                    }
                    else
                    {
                        this.CreateLog(reason2, Path.GetFileName(txtName), "");
                        reason = "MultiFile";
                        reason2 = reason;
                    }                 
                }
            }
        }

        public void CreateLog(string _reason, string _sourceFileName = "", string _targetFile = "")
        {
            string          logFile = ConfigurationManager.AppSettings["logFilePath"];
            StreamWriter    log;
            FileStream      fileStream = null;
            DirectoryInfo   logDirInfo = null;
            FileInfo        logFileInfo;

            logFile     = logFile + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
            logFileInfo = new FileInfo(logFile);
            logDirInfo  = new DirectoryInfo(logFileInfo.DirectoryName);

            if (!logDirInfo.Exists) logDirInfo.Create();

            if (!logFileInfo.Exists)
            {
                fileStream = logFileInfo.Create();
            }
            else
            {
                fileStream = new FileStream(logFile, FileMode.Append);
            }
            log = new StreamWriter(fileStream);

            if (_reason == "NoFile")
            {
                log.WriteLine(System.DateTime.UtcNow.ToString() + "- " + "no file exist");
            }
            else if (_reason == "Success")
            {
                log.WriteLine(System.DateTime.UtcNow.ToString() + "- " + "Header appended and file moved to Archive. " + "incoming file - " + _sourceFileName + " target file - " + Path.GetFileName(_targetFile));
            }
            else if (_reason == "ServiceStart")
            {
                log.WriteLine(System.DateTime.UtcNow.ToString() + "- " + "Header File Service Stared");
            }
            else if (_reason == "ServiceStopped")
            {
                log.WriteLine(System.DateTime.UtcNow.ToString() + "- " + "Header File Service Stopped");
            }
            else if (_reason == "OneFile")
            {
                log.WriteLine(System.DateTime.UtcNow.ToString() + "- " + "Remaining Files in the folder to be processed" + "- " + _sourceFileName);
            }
            else if (_reason == "MultiFile")
            {
                log.WriteLine(_sourceFileName);
            }
            log.Close();
        }     
    }
}

No comments:

Post a Comment