场景- 创建一个能够在用户计算机上添加和删除打印机的应用程序后,我遇到一个关键错误:
1)如果打印队列(System32 \ spool \ PRINTERS)中存在打印作业,这些作业是SPL和SHD文件,则不会删除打印机
2)如果有一个大小为23,000kb的文件,我需要一种方法来停止该过程,直到命令完成为止
我当前的方法流程
Dim p As Process = New Process()
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
p.StartInfo.FileName = "cmd.exe"
For i = 0 To 2
Select Case i
Case 0
'Stop spooler and dependencies
p.StartInfo.Arguments = "/c net stop spooler /yes"
p.Start()
Case 1
'Delete all queues within folder
p.StartInfo.Arguments = "/c del C:\Windows\System32\spool\PRINTERS\*.* /F /Q"
p.Start()
'Delete printer
printer.Delete()
Case 2
'Restart the spooler service
p.StartInfo.Arguments = "/c net start spooler"
p.Start()
End Select
Next
具有线程:
Dim p As Process = New Process()
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
p.StartInfo.FileName = "cmd.exe"
For i = 0 To 2
Select Case i
Case 0
'Stop spooler and dependencies
p.StartInfo.Arguments = "/c net stop spooler /yes"
p.Start()
'Allow time for the application to purge larger file sizes
Threading.Thread.Sleep(2500)
Case 1
'Delete all queues within folder
p.StartInfo.Arguments = "/c del C:\Windows\System32\spool\PRINTERS\*.* /F /Q"
p.Start()
'Delete printer
printer.Delete()
Case 2
'Restart the spooler service
p.StartInfo.Arguments = "/c net start spooler"
p.Start()
Threading.Thread.Sleep(2500)
End Select
Next
这两种方法均无法正常工作,应用程序没有足够的时间停止后台打印程序服务。这意味着将不会删除文件,导致删除打印机时出错。
我希望从该主题中学到什么:
我需要一些有关如何有效操作此过程的指导。非常感谢
答案 0 :(得分:0)
您可以在代码中停止该服务:
Option Infer On
Option Strict On
Imports System.ServiceProcess
'........
Sub StopService(ByVal serviceName As String)
Using sc = New ServiceController(serviceName)
Dim ts = TimeSpan.FromSeconds(30)
Try
sc.Stop()
sc.WaitForStatus(ServiceControllerStatus.Stopped, ts)
log.AppendFormatLine("Stopped {0} service.", serviceName)
Catch ex As InvalidOperationException
log.AppendFormatLine("** Could not stop {0} service because {1}.", serviceName, ex.Message)
Catch ex As TimeoutException
log.AppendFormatLine("** Timeout after waiting {0} seconds for {1} service to stop.", ts.Seconds.ToString)
End Try
End Using
End Sub