我正在努力将VB6项目的部分转换为VB.Net,并且有一些我遇到问题的代码段,因为我似乎无法在VB.Net中找到VB6代码的替代品。这是现在有问题的代码块:
Public Sub ProcessError(ByVal strModule As String, ByVal strProcedure As String, _
ByVal strDescription As String, ByVal bLogError As Boolean, _
ByVal bShowError As Boolean, Optional ByVal strMsg As String)
On Error GoTo 100
Dim intFile As Integer: Dim strPathName As String
strPathName = AddBackSlash(gsLogPath) & gsErrLogName
If bLogError = True Then
If GetFileSize(strPathName) > gcuMaxLogFileSize Then
Call CopyFile(strPathName, strPathName & ".bak")
Call DeleteFile(strPathName)
End If
intFile = FreeFile
Open strPathName For Append As #intFile
Write #intFile, Format(Now, "MMM-DD-YYYY HH:MM:SS AMPM"), strModule, strProcedure, strDescription)
Close #intFile
End If
If bShowError Then
Call Prompt("Error occurred in " & strModule & vbCrLf & "Error Description :" & strDescription, 1, vbRed)
End If
Exit Sub
100:
Close #intFile
End Sub
所以我遇到的问题是:
Open strPathName For Append As #intFile
Write #intFile
Close #intFile
我理解我应该使用StreamWriter
对象来代替这些,但是错误部分会让我失望。如果抛出错误并且它会转到100
标记,那么Close #intFile
如果尚未打开或创建它将如何工作?
对于大多数其他转换烦恼,我已经将此移植到这个上,这让我感到困惑,所以任何帮助都会受到赞赏。谢谢你的时间。
答案 0 :(得分:3)
这可以修复错误,并且还会更新大量代码,以便使用现代VB.Net中更典型的样式和API。为了使其按原样工作,请确保文件顶部有Imports System.IO
指令。
Public Sub ProcessError(ByVal ModuleName As String, ByVal ProcedureName As String, _
ByVal Description As String, ByVal LogError As Boolean, _
ByVal ShowError As Boolean, Optional ByVal Message As String)
If LogError Then
Dim logFile As New FileInfo(Path.Combine(gsLogPath, gsErrLogName))
If logFile.Length > gcuMaxLogFileSize Then
logFile.MoveTo(logFile.FullName & ".bak")
End If
Try
File.AppendAllText(PathName, String.Format("{0:d},""{1}"",""{2}"",""{3}""", DateTime.Now, ModuleName, ProcedureName, Description))
Catch
End Try
End If
If ShowError Then
MsgBox(String.Format("Error occurred in {0}{1}Error Description:{2}", ModuleName, vbCrLf, Description))
End If
End Sub
值得指出的一件事是VB.Net的style guidelines published by Microsoft现在明确推荐匈牙利类型前缀。
答案 1 :(得分:0)
如果您只有一行要写入,您可以使用内置方法为您完成所有工作。
Dim inputString As String = "This is a test string."
My.Computer.FileSystem.WriteAllText(
"C://testfile.txt", inputString, True)