简体   繁体   中英

windows service file delete c#

windows service example code

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?

You can use the OnCustomCommand override, but this only takes an integer as an argument and does not support passing strings to the service.

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.

EDIT: to respond to a question in the comments about how to use OnCustomCommand in a very strange way is as follows.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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