![](/img/trans.png)
[英]Copy and delete the file from the FTP SERVER using Windows Service in c#
[英]windows service file delete c#
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();
}
如何從Windows窗體調用deleteFile(string文件夾) ?
您可以使用OnCustomCommand重寫,但這僅將整數作為參數,並且不支持將字符串傳遞給服務。
其他選項是創建WCF服務或使用遠程處理將所需的信息傳遞給服務並調用delete方法。
編輯:回答注釋中有關如何以一種非常奇怪的方式使用OnCustomCommand的問題,如下所示。
在服務中,您將需要這樣的東西。
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);
}
}
}
在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);
}
這未經測試,僅是概念證明。 同樣,我不建議這樣做,上面的示例只是為了說明如何不在桌面應用程序和服務之間進行這種類型的通信。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.