【发布时间】:2019-02-26 13:25:24
【问题描述】:
我已经设法让服务正常工作,同时将 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 块插入到文本文件中。但是,我已经在一个单独的项目中单独运行代码,并在控制台应用程序中插入到数据库中。
任何帮助表示赞赏,亲切的问候。
【问题讨论】:
-
将你的catch改为catch(Exception ex)然后WriteToFile异常(你的catch块中的ex变量)
-
@Daniel 谢谢 - 出现错误消息:无法打开登录请求的数据库“dbname”。登录失败。 - 我知道这看起来很简单,但是在我的控制台应用程序中,我使用的是确切的代码并且它正在这样做。有什么想法我需要改变吗?
-
太棒了!所以罪魁祸首是你的连接字符串。您是否可能从控制台应用程序中的另一个位置(可能是应用程序配置)中提取它?
-
不,我想在我让它工作后改变它。问题肯定出在连接字符串上,上面代码中显示的连接字符串出现此错误:System.Data.SqlClient.SqlException(0x80131904),快速谷歌并尝试了其中一种解决方案,但后来我得到了这个错误:系统.Data.SqlClient.SqlException (0x80131904)
-
您正在使用 Windows 凭据向 sql 服务器“IntegratedSecurity=true”进行身份验证,Windows 服务可能在服务帐户下运行。在 services.msc 中,您可以右键单击您的服务并选择登录选项卡以本地用户身份运行,您应该能够使用 sql 服务器进行身份验证。这就是为什么它在控制台应用程序中工作但在 win 服务中失败的原因。或者简单地在 sql 中创建一个用户帐户并在连接字符串中使用它而不是集成安全性。
标签: c# database windows-services filesystemwatcher