how to create text file in window service
I have an XML file
<config>
<ServiceName>autorunquery</ServiceName>
<DBConnection>
<server>servername</server>
<user>xyz</user>
<password>klM#2bs</password>
<initialcatelog>TEST</initialcatelog>
</DBConnection>
<Log>
<logfilename>d:\testlogfile.txt</logfilename>
</Log>
<Frequency>
<value>10</value>
<unit>minute</unit>
</Frequency>
<CheckQuery>select * from credit_debit1 where station='Corporate'</CheckQuery>
<Queries total="3">
<Query id="1">Update credit_debit1 set station='xxx' where id=2</Query>
<Query id="2">Update credit_debit1 set station='xxx' where id=4</Query>
<Query id="3">Updat开发者_如何学运维e credit_debit1 set station='xxx' where id=9</Query>
</Queries>
</config>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Xml;
namespace Service1
{
public partial class Service1 : ServiceBase
{
XmlTextReader reader = null;
string path = null;
FileStream fs = null;
StreamWriter sw = null;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1.Enabled = true;
timer1.Interval = 10000;
timer1.Start();
logfile("start service");
}
protected override void OnStop()
{
timer1.Enabled = false;
timer1.Stop();
logfile("stop service");
}
private void logfile(string content)
{
try
{
reader = new XmlTextReader("queryconfig.xml");//xml file name which is in current directory
if (reader.ReadToFollowing("logfilename"))
{
path = reader.ReadElementContentAsString();
}
fs = new FileStream(path, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.Write(content);
sw.WriteLine(DateTime.Now.ToString());
}
catch (Exception ex)
{
sw.Write(ex.ToString());
throw;
}
finally
{
if (reader != null)
reader.Close();
if (sw != null)
sw.Close();
if (fs != null)
fs.Close();
}
}
}
}
My problem is that the file is not created.
I think it is happening probably because you are using a System.Windows.Forms.Timer. It was not designed to work with a windows service. Change your timer component to System.Timers.Timer. This class is suitable for Windows Services.
I suppose service identity has no rights to write to HD. Check system event log for exceptions.
If your file is not created you would very likely get an exception which would appear in event log and your service would terminate as you do not handle any exceptions.
My guess would be that the file is created but not in the location that you expect. To check that either use a hard-coded absolute path or use Process Explorer to find the working folder of your service.
A simple technique for debugging scenarios like this one is to use System.Diagnostics.Trace.WriteLine()
for putting out debug information and then start Debug View from Sysinternals to receive and display the trace messages.
精彩评论