윈도우즈 서비스 만들기

2553 단어
자세히 보기
1. VS-'파일 - '새 항목, 팝업 창에서 Visual C#-'윈도우즈-'윈도우즈 서비스 선택
2. 새 프로젝트에서 서비스 1을 클릭하십시오.cs 파일, 코드 보기로 전환:

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.Timers;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
using System.Net.Mail;

namespace TimedTask
{
    public partial class Service1 : ServiceBase
    {
        Timer timer;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer = new Timer(60000);//1000=1s,   1  
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        protected override void OnStop()
        {
            timer.Stop();
            timer.Dispose();
        }

        //       
        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            string time = DateTime.Now.AddDays(1).ToShortDateString() + " " + DateTime.Now.ToLongTimeString().ToString();

            string filePath = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
            StreamWriter sw = null;
            if (!File.Exists(filePath))
            {
                sw = File.CreateText(filePath);
            }
            else
            {
                sw = File.AppendText(filePath);
            }
            sw.Write("    :" + time + Environment.NewLine);
            sw.Close();
        }        
        
    }
}


3. 프로젝트 생성, bin 디렉터리에exe 파일 생성
4. 시스템에 서비스를 추가합니다.
(1).시스템 디스크 아래의 을 찾습니다.net 경로: 네이티브는 C:\Windows\Microsoft입니다.NET\Framework\v4.0.30319에서 InstallUtil을 찾습니다.exe
(2).프로젝트 파일 경로에서 bin\Debug\프로젝트 이름을 찾습니다.exe
(3).명령줄 도구를 열고 입력: C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe 공백 D:\WebSites\TimedTask\bin\Debug\프로젝트 이름.exe 
성공적으로 실행되면 Windows 서비스에 방금 추가한 서비스 이름이 나타납니다.
참고 중국어 문자 공백은 스페이스바를 두드리는 것을 의미합니다.
5. 서비스를 시작하면 됩니다.
6. 디버그:
서비스가 시작되었을 때 VS에서 디버깅-를 선택하여 프로세스에 추가하면 이 서비스 이름을 찾을 수 있고 디버깅을 추가할 수 있습니다.

좋은 웹페이지 즐겨찾기