使用Windows Service在FileSystemEventHandler上插入数据库

时间:2019-02-26 13:25:25

标签: c# database windows-services filesystemwatcher

我设法使Service正常运行,同时将FileSystemEventHandler插入文本文件中,但是现在需要更改它才能插入数据库和文本文件中。

using System;  
using System.Collections.Generic;  
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;  
using System.IO;  
using System.Linq;  
using System.ServiceProcess;  
using System.Text;  
using System.Threading.Tasks;  
using System.Timers;  
namespace WindowsServiceTest
{
    public partial class Service1 : ServiceBase
    {
        Timer timer = new Timer(); // name space(using System.Timers;)  
        public static string path = ConfigurationManager.AppSettings["findpath"];
        public Service1()
        {
            InitializeComponent();
        } 

        protected override void OnStart(string[] args)
        {
            WriteToFile("Service is started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 10000; //number in milisecinds  
            timer.Enabled = true;
            FileSystemWatcher watcher = new FileSystemWatcher
            {
                Path = path,
                NotifyFilter = NotifyFilters.LastWrite,
            };
            watcher.Created += new FileSystemEventHandler(FileSystemWatcher_Changed);
            watcher.Renamed += new RenamedEventHandler(FileSystemWatcher_Renamed);
            watcher.Changed += new FileSystemEventHandler(FileSystemWatcher_Changed);
            watcher.EnableRaisingEvents = true;
        }

        public static void FileSystemWatcher_Changed(object source, FileSystemEventArgs e)
        {
            using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Database=ServiceTest;Integrated Security=True;"))
            {
                try
                {
                    con.Open();
                    var command = new SqlCommand("Insert into test(URL, Location) values(@URL, @agendaname);", con);
                    command.Parameters.Add("@URL", System.Data.SqlDbType.VarChar, 100).Value = e.Name;
                    command.Parameters.Add("@agendaname", System.Data.SqlDbType.VarChar, 100).Value = "Case History";
                    command.ExecuteNonQuery();
                }
                catch
                {
                    WriteToFile($"Failed to insert: {e.Name} into the database");
                }
            }
        }
        public static void FileSystemWatcher_Renamed(object source, RenamedEventArgs e)
        {
            WriteToFile($"File Renamed: {e.OldFullPath} renamed to {e.FullPath}");
        }
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            WriteToFile("Service is recalled at " + DateTime.Now);
        }
        protected override void OnStop()
        {

            WriteToFile("Service is stopped at " + DateTime.Now);
        }

        public static void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.   
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }
    }
}

我认为数据库插入错误,因为将catch块插入了文本文件。但是,我已经在一个单独的项目中单独运行了代码,并将其插入到控制台应用程序的数据库中。

感谢您的帮助,

1 个答案:

答案 0 :(得分:0)

Windows服务与控制台应用程序在不同的安全上下文下运行。正如评论所揭示的,该异常与您的连接字符串有关。 如果我们分析connectiong字符串,我们可以看到您正在使用IntegratedSecurity="True".进行身份验证,因为Windows服务正在 服务帐户身份验证失败。我已经指定了2个解决方案。

选项1:让服务以Windows帐户身份运行(不推荐,但可以用于测试)

  1. 打开运行框(Win Flag + R)
  2. 键入Services.MSC
  3. 找到您的服务并右键单击属性
  4. 选择登录标签
  5. 输入Windows身份验证用户名和密码以使服务运行为

选项2:创建SQL Server帐户

  1. 在SQL中为数据库创建用户名和密码
  2. 更新连接字符串以指定创建的新用户名和密码