在文件夹中创建文件时执行web api调用

时间:2018-02-16 06:13:51

标签: c# windows asp.net-web-api windows-services

每当在指定文件夹上创建新文件时,我们如何在Windows服务器上执行web api调用

我正在考虑服务器上的Windows服务,在无限循环上运行并查找其中存在的文件。但不太确定性能影响。此外,如果服务自动关闭,整个假设将失败。任何其他更好的方法也是如此。

2 个答案:

答案 0 :(得分:1)

有点评论,因此想到发帖作为答案。所以回答:每当在指定文件夹上创建新文件时,我们如何在Windows服务器上执行web api调用

  

每当在指定文件夹上创建新文件时

您可以使用FileSystemWatcher课程和每个文档

  

收听文件系统更改通知并在何时引发事件   目录或目录中的文件发生更改。

因此,监听事件并在处理程序上调用您的Api端点

答案 1 :(得分:1)

我已经构建了许多文件处理应用程序,Windows服务是一个不错的选择。而不是FileSystemWatcher,我会创建3个文件夹;在,完成和错误。您的服务只需要遍历In Folder中的所有文件进行处理,然后在处理时将它们复制到Done文件夹,如果无法处理则将其复制到错误文件夹。通过这种方式,您可以轻松查看已完成的操作和错误以及剩下的工作。该服务还将收集剩下的内容。

服务类可以非常轻量级,只需要调用处理方法:

namespace App.WindowsService
{
    public partial class FileProcessingService : ServiceBase
    {
        #region System Components

        private readonly System.Timers.Timer _processingTimer;
        private static readonly Logger Logger = Logger.Get();

        #endregion

        #region Service Properties

        private int _interval;
        private bool Stopped { get; set; } = true;

        /// <summary>
        /// Returns the interval for processing
        /// </summary>
        private int Interval
        {
            get
            {
                if (_interval <= 0)
                {
                    return _interval = Settings.ServiceInterval;
                }

                return _interval;
            }
        }

        #endregion

        #region Constructor

        public FileProcessingService()
        {
            InitializeComponent();
            CanShutdown = true;
            _processingTimer = new System.Timers.Timer();
            _processingTimer.Elapsed += ProcessingTimerElapsed;
        }

        #endregion

        #region Service Events

        protected override void OnStart(string[] args)
        {
            _processingTimer.Interval = Interval;
            _processingTimer.Start();
            Stopped = false;
            Logger.Trace("Service Started");
        }

        protected override void OnStop()
        {
            _processingTimer.Stop();
            Stopped = true;
            Logger.Trace("Service Stopped");
        }

        protected override void OnShutdown()
        {
            OnStop();
            base.OnShutdown();
        }

        #endregion

        #region Processing Timer Elapsed Event

        private void ProcessingTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Logger.MethodEntry();

            try
            {
                _processingTimer.Stop();
                Process();
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch
            {
            }

            if (!Stopped)
            {
                _processingTimer.Start();
            }
        }

        #endregion

        #region Public Methods

        public void Process()
        {
            // Call your processing method
        }

        #endregion
    }
}