Visual Basic - StreamWriter - 如何跳到下一行,如果所述行不为空



嘿,所以我正在尝试做一个简单的流词者,以将员工信息添加到文本文件(我已经有一个工作streamreader登录页面),文本文件有一些示例数据,但是还必须能够将新数据写入其中。

我的问题是,仅在初始启动时,我对数据的初始撰写就与文本文件中的最后一行示例数据(而不是在下一个空白行上)写入的行写作。这是在启动后首次尝试编写数据之后的文本文件的外观。

  • 乔恩,琼斯
  • 哈利,波特
  • 詹姆斯,冈恩
  • 基兰,基兰森
  • 我,toogreg,

"我也是我的最后一行数据,"灰色,哈迪"是我通过StreamWriter编写的第一个数据

我在这里进行了一些研究,并找到了如何编写空白行的示例第一次在任何给定的启动中,如果每次都留下空白行,那么如果我进行了两次尝试使用StreamWriter,则看起来像

  • 乔恩,琼斯
  • 哈利,波特
  • 詹姆斯,冈恩
  • 基兰,基兰森
  • 我,也
  • 格雷格,哈迪
  • 空白行
  • 汤姆,哈迪

然后将启用空白登录以工作。

这是我的streamwriter

的代码
'StreamReader to check if a line is empty or not
        Dim StaffReader As StreamReader = File.OpenText("StaffInfo.txt")
        strLine = StaffReader.ReadLine()
        StaffReader.Close()
        'Streamwriter for adding staff log in to textfile
        Dim FileCheck As StreamWriter = File.AppendText("StaffInfo.txt")
        FileCheck.WriteLine(strStaffUsername2 & "," & strStaffPass2)
                FileCheck.Close(``)
                MessageBox.Show(strStaffUsername2 & " added to the file. ", "Data Added")
                txtUser2.Clear()
                txtUser2.Focus()
                txtPass2.Clear()

我只希望它跳到下一个空白行,如果它要编写的行上有任何字符。

您要寻找的是要点,如果文件中的最后一行包含返回马车。如果它确实包含运输返回,则可以用书面代码附加文本。但是,如果它不包含马车返回,则必须将第一行带有托架返回。
因此,首先,您必须检查您的最后一行是否有马车返回。您可以通过这样的函数来执行此操作:

Private Function DoesLastLineHasCarriagReturn(Filename As String) As Boolean
    Dim s as String = ""
    using stream = New StreamReader(Filename)
        ' we have to read the last two characters
        stream.BaseStream.Seek(-2,SeekOrigin.End)
        dim c_beforeLast as Integer = stream.Read()
        Dim c_Last As Integer = stream.Read()
        ' if the last character is 10 -> we have a carriage return. Windows and Linux just use different encodings
        if (c_Last =10)
            If(c_beforeLast = 13)
                Console.WriteLine("Ends with carriage return CRLF (Windows)")
            Else 
                Console.WriteLine("Ends with carriage return LF (UNIX, OSX )")
            End If
            return true
        Else 
            Console.WriteLine("Does not end with Carriage return")     
        End If
    End Using
    return false      
End Function

然后在开始写入文件时,首先必须调用该函数。在这里,您的代码看起来像:

If DoesLastLineHasCarriagReturn("StaffInfo.txt")
    Dim FileCheck As StreamWriter = File.AppendText("StaffInfo.txt")
   FileCheck.WriteLine("Greg" & "," & "Hardy")
   FileCheck.Close()
Else 
    Dim FileCheck As StreamWriter = File.AppendText("StaffInfo.txt")
    FileCheck.WriteLine(vbCrLf + "Greg" & "," & "Hardy")
    FileCheck.Close()
End If

顺便说一句,我建议您使用using语句自动关闭流:

If DoesLastLineHasCarriagReturn("StaffInfo.txt")
    Using writer As New StreamWriter("StaffInfo.txt", True)
        writer.WriteLine("Greg" & "," & "Hardy")
    End Using
Else 
    Using writer As New StreamWriter("StaffInfo.txt", True)
        writer.WriteLine(vbCrLf +"Greg" & "," & "Hardy")
    End Using
End If

,由于我们正在处理文本文件而不做任何花哨的事情,因此我们可以在System.io中使用文件类。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim FilePath = "TestFiles/File1.txt"
    'Dump contents of file
    Dim fileContents As String = File.ReadAllText(FilePath)
    'Extract the last 2 characters in the contents
    Dim NextToLast As String = fileContents(fileContents.Length - 2)
    Dim LastCharacter As String = fileContents(fileContents.Length - 1)
    'Check if we have a CrLf an if not add a new line
    If Not NextToLast = Chr(13) AndAlso Not LastCharacter = Chr(10) Then
        File.WriteAllText(FilePath, Environment.NewLine)
    End If
    'Write to the file
    File.AppendAllLines(FilePath, {TextBox1.Text})
End Sub

要显示您的文本文件,请在您的表单中添加列表框。

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    'Put the contents of the file into a string array of lines
    Dim staff() As String = File.ReadAllLines("TestFiles/File1.txt")
    ListBox1.DataSource = staff
End Sub

相关内容

最新更新