目前项目中需要在客户服务器安装一个程序,让我们的服务器可以调用几个客户的存储过程。
我想做一个exe文件,让用户安装就好,安装过后程序不在前台启动。
度娘教我原来要用windows服务,但是过程中出了一点小问题,记录在这里。
抱歉原文我找不到了,跟原文作者道歉,大意是创建一个windows服务。然后代码是按时间写一点文字到本地文件。
using System;
using System.IO;
namespace Windows服务程序测试01
{
class FileOpetation
{
public static void SaveRecord(string content)
{
if (string.IsNullOrEmpty(content))
{
return;
}
FileStream fileStream = null;
StreamWriter streamWriter = null;
try
{
//ApplicationBace在bin文件夹下Debug文件夹,或者Realease文件夹下
string path = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, string.Format("0:yyyyMMdd", DateTime.Now));
using (fileStream = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write(content);
if (streamWriter != null)
{
streamWriter.Close();
}
}
}
if (fileStream != null)
{
fileStream.Close();
}
}
catch (Exception)
{
throw;
}
}
}
}
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.Threading;
using System.Threading.Tasks;
namespace Windows服务程序测试01
{
public partial class Service1 : ServiceBase
{
System.Threading.Timer recordTimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
IntialSaveRecord();
}
protected override void OnStop()
{
}
private void IntialSaveRecord()
{
TimerCallback timerCallback = new TimerCallback(CallbackTask);
AutoResetEvent autoEvent = new AutoResetEvent(false);
recordTimer = new System.Threading.Timer(timerCallback, autoEvent, 10000, 60000 * 10);
}
private void CallbackTask(object stateInfo)
{
FileOpetation.SaveRecord(string.Format(@"当前时间:{0},状况:程序正在运行", DateTime.Now));
}
}
}
可是F5运行这个程序
二问度娘,度娘说:
将服务程序service1.cs 切换到视图模式,用鼠标右键单击设计视图选择“添加安装程序”选项,此后在项目中自动增加了一个ProjectInstaller.cs。
设置serviceInstaller1组件属性,
ServiceName=MyServiceLog安装服务器名字;
StartType=Automatic 开机自动启动
设计serviceProcessInstaller1的属性Account=LocalSystem;
运行编译,一个简单的windows服务已经开发完成
注:如果在代码中的文件路径写成如下“service.txt”,那么此时文件保存在C:\WINDOWS\system32文件夹中。
安装window服务
安装命令:InstallUtil.exe Windows服务程序测试01.exe
InstallUtil存在路径为:C:\WINDOWS\Microsoft.NET\Framework\.NET版本号
复制C:\WINDOWS\Microsoft.NET\Framework\版本号 路径中的InstallUtil.exe 到bin/debug或bin/release文件夹中,在命令行窗口中直接运行命令
InstallUtil.exe MyServiceLog.exe,在系统中注册这个服务,使它建立一个合适的注册项,如下图:
按度娘说的问题又来了
然后我点F5,照旧,好吧我想多了。
我去服务里找
有啦有啦