0

There is a service for monitoring the network folder, it performs its functions correctly, but there is one nuance: if the network is disconnected, then after the connection is restored, the service ceases to perform its functions, or the service is turned off. It solves only a restart. Can someone tell me how to monitor the connection? (tried through ping, but the result is the same).

Code

namespace CopyCema
{
    public class CopyCema : ServiceBase
    {

        public const string MyServiceName = "CopyCema";

        private void InitializeComponent()
        {
            this.ServiceName = MyServiceName;
        }

        Logger logger;

        public CopyCema()
        {
            InitializeComponent();
            this.CanStop = true;
            this.CanPauseAndContinue = true;
            this.AutoLog = true;
            this.CanPauseAndContinue = true;
        }

        protected override void OnStart(string[] args)
        {   
            logger = new Logger();
            Thread loggerThread = new Thread(new ThreadStart(logger.Start));
            loggerThread.Start();

        }

        protected override void OnStop()
        {
            logger.Stop();
            Thread.Sleep(1000);
        }
    }

    class Logger
    {
        FileSystemWatcher watcher;
        object obj = new object();
        bool enabled = true;

        public string _Day()
        {
            string DTime = "";
            var date = DateTime.Now;
            int dayOfWeek = (int)date.DayOfWeek;
            if (dayOfWeek == 1)
            {
                DTime = DateTime.Now.AddDays(-3).ToShortDateString().Replace("2019", "19");
            }
            else
            {
                DTime = DateTime.Now.AddDays(-1).ToShortDateString().Replace("2019", "19");
            }
            return DTime;
        }

        public Logger()
        {

                string NetDir = @"\\<PC in LAN>\backup\"+_Day();
                string DestDir = @"D:\backupchik\"+_Day();

                DirectoryInfo NetDirInfo = new DirectoryInfo(NetDir);

                if (!NetDirInfo.Exists)
                {
                    NetDirInfo.Create();
                }

                string[] Files = Directory.GetFiles(NetDir);

                if (Files.Length!=0)
                {
                    DirectoryInfo DDirInfo = new DirectoryInfo(DestDir);

                    if (!DDirInfo.Exists)
                    {
                        DDirInfo.Create();
                    }

                    foreach(string f in Files)
                    {
                        FileInfo FInfo = new FileInfo(DestDir + @"\" + Path.GetFileName(f));
                        if (!FInfo.Exists)
                        {
                            File.Copy(f, DestDir + @"\" + Path.GetFileName(f));
                        }

                    }

                }

                watcher = new FileSystemWatcher(@"\\<PC in LAN>\backup\"+_Day());
                watcher.Deleted += Watcher_Deleted;
                watcher.Created += Watcher_Created;
                watcher.Changed += Watcher_Changed;
                watcher.Renamed += Watcher_Renamed;


        }

        public void Start()
        {
            watcher.EnableRaisingEvents = true;
            while(enabled)
            {
                Thread.Sleep(1000);
            }
        }
        public void Stop()
        {
            watcher.EnableRaisingEvents = false;
            enabled = false;
        }
        // переименование файлов
        private void Watcher_Renamed(object sender, RenamedEventArgs e)
        {
            string fileEvent = "переименован в " + e.FullPath;
            string filePath = e.OldFullPath;
            RecordEntry(fileEvent, filePath);
        }
        // изменение файлов
        private void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            string fileEvent = "изменен";
            string filePath = e.FullPath;
            RecordEntry(fileEvent, filePath);
        }
        // создание файлов
        private void Watcher_Created(object sender, FileSystemEventArgs e)
        {

            string fileEvent = "создан";
            string filePath = e.FullPath;
            RecordEntry(fileEvent, filePath);

            string sourceDir = @"\\<PC in LAN>\backup\"+_Day();
            string DDir = @"D:\backupchik\"+_Day();

            Thread.Sleep(2000);
            Task Tsk1 = new Task( () => copyD(sourceDir, DDir));
            Tsk1.Start();
        }

        public void copyD(string source0, string source2)
        {
            string[] files = Directory.GetFiles(source0);
            DirectoryInfo DDirInfo = new DirectoryInfo(source2);
            string destDir = "";

            if (!DDirInfo.Exists)
            {
                DDirInfo.Create();
            }

            destDir = @"D:\backupchik\"+_Day();

            foreach(string str in files)
            {   
                FileInfo Finfo = new FileInfo(destDir + @"\" + Path.GetFileName(str));
                FileInfo FinfoS = new FileInfo(str);
                if (!Finfo.Exists)
                {
                    if (FinfoS.Exists)
                    {
                        File.Copy(str, destDir + @"\" + Path.GetFileName(str), true);
                    }
                }
            }


        }

        // удаление файлов
        private void Watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            string fileEvent = "удален";
            string filePath = e.FullPath;
            RecordEntry(fileEvent, filePath);
        }

        private void RecordEntry(string fileEvent, string filePath)
        {
            lock (obj)
            {

                    using (StreamWriter writer = new StreamWriter(@"C:\Users\111\Desktop\templog.txt", true))   
                    {
                        writer.WriteLine(String.Format("{0} файл(папка) {1} был(а) {2}", 
                            DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"), filePath, fileEvent));
                        writer.Flush();
                    }


            }

        }

    }

}
  • https://stackoverflow.com/questions/178147/how-can-i-verify-if-a-windows-service-is-running – Train Dec 10 '19 at 00:30
  • If the service is hanging, you need to identify the line of code that it is getting stuck on and share it with us. If it is crashing due to an unhandled exception, share the exception and the code that is raising it. From just your high-level description there is no way to solve the problem. – John Wu Dec 10 '19 at 01:38
  • When you try to start a service when there is no connection to a network resource, only one error occurs: the service cannot be started. System.IO.DirectoryNotFoundException: could not find part of the path "\\ path. But if the network was disconnected and then turned on again while the service was running, it does not display an error. In Windows Services, it displays that the service is running. But it does not move the files and the log does not write until you restart it. – Gogga Budulai Dec 11 '19 at 02:57

0 Answers0