我试图用Oracle Db Access创建Windows服务,但是当我运行该服务时却没有运行数据库访问,只能在分配的文本文件上打印服务启动消息。
但是我将相同的代码分配给C#控制台应用程序,即使数据库访问部分也一切正常,我还缺少什么?
这是我的代码:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteToFile("Service is Started at" + DateTime.Now);
string finalName = string.Empty;
DataSet ds;
try
{
DataAccess dataAccess = new DataAccess();
OracleParameter[] paramArray = new OracleParameter[1];
paramArray[0] = new OracleParameter("P_ResultSet", OracleDbType.RefCursor);
paramArray[0].Direction = ParameterDirection.Output;
ds = dataAccess.ReadDataBySP(paramArray, "SP_GET_ALL_SCREEN");
if (ds != null)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
finalName += row["DISPLAYNAME"].ToString();
}
}
}
catch (Exception ex)
{
throw ex;
}
WriteToFile(finalName);
}
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))
{
// creating file
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using(StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
}
请注意,WriteToFile()方法可以正常工作。