Как скопировать файл из папки в другую папку с помощью Windows Service C #

1

Как скопировать файл из папки в другую папку с помощью службы Windows С#

Я пробую этот код скопировать файл каждые 30 секунд. Но цикл времени в порядке, поэтому копирование невозможно. Поэтому я использую Visual Studio 2012. Я установлю Windows Service с командной строкой. Как исправить этот код.

using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
using System.IO;
using TestWindowService;

namespace TestCopy
{
    public partial class Copy : ServiceBase
    {
        private FileSystemWatcher watcher;
        private System.Timers.Timer timer1 = null;
        public Copy()
        {
           InitializeComponent(); 
        }

        protected override void OnStart(string[] args)
        {
            //File.Copy(@"C:\input\*.*", @"D:\output\*.*");
            Library.WriteErrorLog("Test window service started");
            timer1 = new System.Timers.Timer();
            this.timer1.Interval = 30000; //every 30 secs
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;
            watcher = new FileSystemWatcher();
            watcher.Path = "C:\\INPUT\\";
            watcher.Filter = "*.*";
            watcher.EnableRaisingEvents = true;
        }

        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            String output_dir = "D:\\OUTPUT\\";
            String output_file = Path.Combine(output_dir, e.Name);
            File.Copy(e.FullPath, output_file);
            // File.Copy() works here
            Library.WriteErrorLog("File copy success");
        }

        private void timer1_Tick(object sender, ElapsedEventArgs e)
        {
            watcher.Created += new FileSystemEventHandler(OnCreated);                 
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            Library.WriteErrorLog("Test window service stopped"); 
        }
    }
}
Теги:
windows-services
visual-studio-2012

1 ответ

2
Лучший ответ

Вы добавляете обработчик в FileSystemWatcher.Created каждые 30 секунд.

Если я правильно понимаю, вы хотите выполнить копирование каждые 30 секунд.

using System;
using System.Collections.Concurrent;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
using TestWindowService;

namespace TestCopy
{
    public partial class Copy : ServiceBase
    {
        private FileSystemWatcher watcher;
        private System.Timers.Timer timer;
        private ConcurrentQueue<FileInfo> lastCreated;

        public Copy()
        {
            InitializeComponent();

            timer = new System.Timers.Timer();
            timer.Interval = 30000; //every 30 secs
            timer.Elapsed += (s, e) => CopyFiles();

            watcher = new FileSystemWatcher();
            watcher.Path = "C:\\INPUT\\";
            watcher.Filter = "*.*";
            //schedule the file for copying on the next tick
            watcher.Created += (s, e) => lastCreated.Enqueue(new FileInfo(e.FullPath));
        }

        protected override void OnStart(string[] args)
        {
            timer.Enabled = true;
            watcher.EnableRaisingEvents = true;

            Library.WriteErrorLog("Test window service started");
        }

        private void CopyFiles()
        {
            String output_dir = "D:\\OUTPUT\\";

            FileInfo fi;
            while (lastCreated.TryDequeue(out fi))
                if (fi.Exists)
                    fi.CopyTo(Path.Combine(output_dir, fi.Name));

            Library.WriteErrorLog("File copy success");
        }

        protected override void OnStop()
        {
            watcher.EnableRaisingEvents = false;
            timer.Enabled = false;

            //empty the queue
            FileInfo fi;
            while (!lastCreated.IsEmpty)
                lastCreated.TryDequeue(out fi);

            Library.WriteErrorLog("Test window service stopped");
        }
    }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню