【问题标题】:Windows service is not working as expected - C#Windows 服务未按预期工作 - C#
【发布时间】:2017-10-21 22:19:53
【问题描述】:

我使用FileWatcher 类构建了一个Windows 服务。它必须检测文件夹中的传入文件并将它们移动到新位置。

我的代码作为控制台应用程序运行良好,但不能作为 Windows 服务运行。文件仅保留在 Source 文件夹中。他们没有移动到目的地。我已授予对在本地系统帐户中运行的文件夹和服务的完全访问权限。你能指出错误吗。提前致谢。

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.Tasks;
using System.IO;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            bulk_watch();
        }

        public static void bulk_watch()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"C:\Users\ADMIN\Downloads\FW_Source";            
            watcher.NotifyFilter = NotifyFilters.LastWrite;     
            watcher.Filter = "*.*";                              
            watcher.Changed += new FileSystemEventHandler(OnChanged); 
            watcher.EnableRaisingEvents = true;

        }

        public static void OnChanged(object sender, FileSystemEventArgs e)
        {


            DirectoryInfo directory = new DirectoryInfo(@"C:\Users\IBM_ADMIN\Downloads\FW_Source");
            FileInfo[] files = directory.GetFiles("*.*");
            foreach (var f in files)
            {

               File.Move(f.FullName, System.IO.Path.Combine(@"C:\Users\ADMIN\Downloads\FW_Dest", Path.GetFileName(f.FullName)));

            }

        }

        protected override void OnStop()
        {



        }
    }
}

【问题讨论】:

  • 什么不起作用?您是否尝试过调试 Windows 服务?请提供更多关于不正常的细节。
  • C:\Users\ADMIN 权限不足?
  • 苍蝇没有移动到目的地。该文件保留在源文件夹中
  • @duDE。我已授予对该文件夹的完全访问权限。该代码作为控制台应用程序运行良好。但不能作为 Windows 服务。

标签: c# .net service windows-services file-watcher


【解决方案1】:

默认情况下,Windows 服务在 LocalSystem 帐户下运行(除非您在安装它们时指定另一个帐户)。您需要授予此帐户对这两个文件夹的访问权限。

【讨论】:

  • 嗨。我在本地系统下运行 Windows 服务,并且也获得了对文件夹的完全访问权限。
【解决方案2】:

使用以下命令创建带有用户名和密码的服务:

sc create "ServiceName" binPath= "G:\services\service.exe" DisplayName= "ServiceName" start= "auto" obj= "username"   password= "password"

替换: ServiceName、exe 文件位置、DisplayName、用户名和密码。

【讨论】:

  • 嗨。谢谢您的评论。有没有办法在没有用户 ID 和密码的情况下运行上述程序..?
  • 该服务需要足够的权限才能访问在这种情况下无法访问的文件,因为文件夹位置位于管理员用户的私人文件夹位置。您可以将文件位置移动到通用驱动器(C 驱动器除外)或使用管理员用户名和密码。
  • 当您将它作为控制台应用程序运行时,它使用您的用户名来访问文件,因此它当时正在工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多