简体   繁体   English

Windows服务文件删除C#

[英]windows service file delete c#

windows service example code Windows服务示例代码

using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace file_delete
{
    public partial class file_delete : ServiceBase
    {  
        public file_delete()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {           
        }
        private void deleteFile(string folder)
        {
         System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(folder);
         System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");
           foreach (System.IO.FileInfo fi in fileNames)
           {              
               fi.Delete();               
           }

How can I call the deleteFile(string folder) from windows forms? 如何从Windows窗体调用deleteFile(string文件夹)

You can use the OnCustomCommand override, but this only takes an integer as an argument and does not support passing strings to the service. 您可以使用OnCustomCommand重写,但这仅将整数作为参数,并且不支持将字符串传递给服务。

The other options would be to create a WCF service or use Remoting to pass the information you need to the service and call the delete method. 其他选项是创建WCF服务或使用远程处理将所需的信息传递给服务并调用delete方法。

EDIT: to respond to a question in the comments about how to use OnCustomCommand in a very strange way is as follows. 编辑:回答注释中有关如何以一种非常奇怪的方式使用OnCustomCommand的问题,如下所示。

In the service you would need something like this. 在服务中,您将需要这样的东西。

private const int CMD_INIT_DELETE = 1;
private const int CMD_RUN_DELETE = 0;

private bool m_CommandInit = false;
private StringBuilder m_CommandArg = new StringBuilder();

protected override void OnCustomCommand(int command)
{
    if (command == CMD_INIT_DELETE)
    {
        this.m_CommandArg.Clear();
        this.m_CommandInit = true;
    }
    else if (this.m_CommandInit)
    {
        if (command == CMD_RUN_DELETE)
        {
            this.m_CommandInit = false;
            this.deleteFile(this.m_CommandArg.ToString());
        }
        else
        {
            this.m_CommandArg.Append((char)command);
        }
    }
}

In the windows form application you would have something like this 在Windows窗体应用程序中,您将具有以下内容

private const int CMD_INIT_DELETE = 1;
private const int CMD_RUN_DELETE = 0;

private void RunServiceDeleteMethod(string delFolder)
{
    serviceController1.ExecuteCommand(CMD_INIT_DELETE);

    foreach (char ch in delFolder)
        serviceController1.ExecuteCommand((int)ch);

    serviceController1.ExecuteCommand(CMD_RUN_DELETE);
}

THIS IS NOT TESTED and only a proof of concept. 这未经测试,仅是概念证明。 Again, I DO NOT recommend doing it this way and the above example is only to show how NOT to do this type of communications between desktop applications and services. 同样,我不建议这样做,上面的示例只是为了说明如何不在桌面应用程序和服务之间进行这种类型的通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM