为和服务器时间校时,我写了如下代码!
'**********************设置本机时间与服务器时间同步
Public Function SetSameTimeToServer(ByVal strServerName As String, Optional ByVal bShowMsgError As Boolean = False) As Boolean
'strServerName为与其同步的服务器名称。
'bShowMsgError为是否显示错误消息,默认为不显示。
'返回命令执行是否成功
Dim strShell As String
strShell = " time " & Chr(34) & "\" & strServerName & Chr(34) & " /set /yes"
Dim a As New Process
With a.StartInfo
.RedirectStandardError = True
.UseShellExecute = False '是否使用SHELL启动
.CreateNoWindow = True '是否启动新窗口,显示DOS窗口
.WindowStyle = ProcessWindowStyle.Hidden '窗口最小化运行
.FileName = "net"
.Arguments = strShell
End With
a.Start() '启动执行
While Not a.HasExited '等待执行完成
System.Threading.Thread.Sleep(100)
End While
If Val(a.ExitCode.ToString) = 0 Then '如果成功则为0。
SetSameTimeToServer = True
Else
If bShowMsgError Then '是否显示错误提示
Dim s As String
s = vbCrLf & Replace(a.StandardError.ReadToEnd.ToString, vbCrLf, " ")
MsgBox("设置与服务器 " & strServerName & " 时间同步出现错误!" & s, MsgBoxStyle.Critical)
End If
SetSameTimeToServer = False
End If
End Function
可是在WINDOWS98下出现程序死掉的现象,而其它操作系统正常!
---------------------------------------------------------------
楼主这么大方,给你写点代码吧
在98系统执行时可以考虑使用输出重定向。
下面是我修改后并测试通过的代码
'**********************设置本机时间与服务器时间同步
Public Function SetSameTimeToServer(ByVal strServerName As String, Optional ByVal bShowMsgError As Boolean = False) As Boolean
'strServerName为与其同步的服务器名称。
'bShowMsgError为是否显示错误消息,默认为不显示。
'返回命令执行是否成功
Dim strShell As String
strShell = " time " & Chr(34) & "\" & strServerName & Chr(34) & " /set /yes"
Dim a As New Process
Dim sFileBat As String = "tmp.bat"
Dim sFileOut As String = "c:\tmp.txt"
Dim FStreamBat As IO.FileStream '用于打开bat文件
Dim SRBat As IO.StreamWriter '写入方式
FStreamBat = New IO.FileStream(sFileBat, IO.FileMode.Append, IO.FileAccess.Write)
SRBat = New IO.StreamWriter(FStreamBat) '打开bat文件
SRBat.WriteLine("net " & strShell & " >>" & sFileOut)
SRBat.Close()
With a.StartInfo
.UseShellExecute = True '是否使用SHELL启动
.CreateNoWindow = True '是否启动新窗口,显示DOS窗口
.WindowStyle = ProcessWindowStyle.Hidden '窗口最小化运行
.FileName = sFileBat
'.Arguments = strShell & " >>c:\tmp.txt"
End With
a.Start() '启动执行
While Not a.HasExited '等待执行完成
System.Threading.Thread.Sleep(1000)
a.Kill()
End While
Dim FStreamOut As IO.FileStream '用于打开DEVICEST.TXT文件
Dim SROut As IO.StreamReader '只读方式
Dim s As String
While True
Try
FStreamOut = New IO.FileStream(sFileOut, IO.FileMode.Open, IO.FileAccess.Read)
SROut = New IO.StreamReader(FStreamOut) '打开DEVICEST.TXT文件
s = SROut.ReadToEnd()
If InStr(s, "successfully") > 0 Or InStr(s, "成功") > 0 Then
SetSameTimeToServer = True
Else
If bShowMsgError Then '是否显示错误提示
MsgBox("设置与服务器 " & strServerName & " 时间同步出现错误!" & vbCrLf & s, MsgBoxStyle.Critical)
End If
SetSameTimeToServer = False
End If
SROut.Close()
Exit While
Catch ex As Exception
End Try
System.Threading.Thread.Sleep(100)
End While
Try '删除临时文件
IO.File.Delete(sFileOut)
Catch ex As Exception
End Try
Try '删除临时文件
IO.File.Delete(sFileBat)
Catch ex As Exception
End Try
End Function