删除C:\Windows\Temp内容的Windows服务
我有一个用vb.net编写的windows服务,它每隔几分钟删除一个文件夹的内容,即该文件夹中的所有文件、子文件夹和文件 我需要更改服务,以便它现在删除C:\Windows\Temp文件夹的内容 当我在服务中编辑路径,然后重新编译并重新安装时,服务不会删除C:\Windows\Temp的内容 我甚至添加了代码来处理任何打开/锁定的文件,这样删除过程就可以继续,但仍然没有任何结果删除C:\Windows\Temp内容的Windows服务,windows,vb.net,service,Windows,Vb.net,Service,我有一个用vb.net编写的windows服务,它每隔几分钟删除一个文件夹的内容,即该文件夹中的所有文件、子文件夹和文件 我需要更改服务,以便它现在删除C:\Windows\Temp文件夹的内容 当我在服务中编辑路径,然后重新编译并重新安装时,服务不会删除C:\Windows\Temp的内容 我甚至添加了代码来处理任何打开/锁定的文件,这样删除过程就可以继续,但仍然没有任何结果 Sub ClearWinTempDirectory(folder As String) 'Loop o
Sub ClearWinTempDirectory(folder As String)
'Loop over the subdirectories and remove them with their contents
For Each d In Directory.GetDirectories(folder)
Directory.Delete(d, True)
Next
' Finish removing also the files in the root folder
For Each f In Directory.GetFiles(folder)
Try
File.Delete(f)
Catch e As System.IO.IOException
Console.WriteLine(e.Message)
End Try
Next
COBWtl.WriteEntry("All files and folders in the " & folder & " directory that
are not currently locked by applications or processes Have been deleted",
EventLogEntryType.Information, eventID:=9995)
End Sub
我希望有人能帮助我确定为什么当指向C:\Windows\Temp时此服务不起作用,但当删除C:\MyTestFolder中的文件和文件夹时,它可以正常工作
我的服务以LocalSystem运行,系统对C:\Windows\Temp拥有完全控制权
我还将其更改为作为管理员帐户运行,但这也不起作用
我可以将相同的代码放入非服务exe并双击它,它可以工作并删除C:\Windows\Temp的内容-因此我完全不知所措,希望有人能为我指出正确的方向,找出问题所在
我提供了进程监视结果,这似乎表明服务正在访问C:\windows\temp,这令人困惑,因为我将一些测试文件放在那里,这些文件在进程中没有打开或保留,并且没有被删除
我能够解决我自己的问题。以下是我的发现: 服务已成功访问C:\Windows\Temp,但由于两个异常而失败: 1权限异常,由于权限原因拒绝访问子文件夹或文件 2 IO问题,因为文件已打开或正在使用 在我的代码中,我只检查System.IO.Exceptions,因此当它遇到访问失败异常时,它将中断 一旦我发现了这一点,我修改了catch上的异常处理,以便它检查所有异常 因此,代码从上面列出的更改为此
Sub ClearWinTempDirectory(folder As String)
'Loop over the subdirectories and remove them with their contents
For Each d In Directory.GetDirectories(folder)
Try
Directory.Delete(d, True)
Catch e As System.Exception
COBWtl.WriteEntry("The directory " & d & " is
currently locked or is inaccessable and will not be deleted.",
EventLogEntryType.Information, eventID:=9997)
End Try
Next
' Finish the files in the root folder
For Each f In Directory.GetFiles(folder)
Try
File.Delete(f)
Catch e As System.Exception
COBWtl.WriteEntry("The file " & f & " in directory " & folder
& " is currently locked or is inaccessable and will not be
deleted.", EventLogEntryType.Information, eventID:=9997)
End Try
Next
COBWtl.WriteEntry("All files and folders in the " & folder & "
directory that are not currently locked by applications or processes
Have been deleted", EventLogEntryType.Information, eventID:=9995)
End Sub
问题已解决。为什么不在堆栈溢出时询问?是的,他们删除了我的帖子,因为我的帖子脱离了主题。你怎么会认为我的帖子是关于主题的呢?也许我不太清楚在stackexchange中应该如何或在哪里发布。我想我把它贴到了程序员区,上面有VB.Net、Windows和服务标签。。。也许我没有把它贴在正确的地方。我第一次在stack exchange上发布。。很抱歉