0

我对 .netFrameWork 4.0 上的 VB.NET 项目有两个问题

1:例如我有文本文件“textfile1.txt”现在程序需要找到“//This Line”行并在“//This Line”之后替换下一行

示例:在 textfile1.txt 中

//This Line
Some Code here

我需要在这里用 TextBox1.text 中的文本替换一些代码

2:我有文本文件“MultiLineTextBox1”现在程序需要按名称从 MultiTextBox1 中逐行杀死进程

示例:在 MultiLineTextBox1

notepad
mspain

记事本和MSPaint需要被杀死......

4

1 回答 1

1

根据我从您的问题中了解到的情况,这就是您所追求的。现在,如果有任何调整,请随时发表评论。

Private Sub Question1()
    Dim list = File.ReadAllLines("yourFilePath").ToList()
    Dim itemCount = list.Count

    For i As Integer = 0 To itemCount - 1
        If list(i) = "//This Line" AndAlso Not ((i + 1) > itemCount) Then
            list(i + 1) = TextBox1.Text
        End If
    Next

    KillProcesses(list)
End Sub

Private Sub Question2()
    Dim list = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.None).ToList()
    KillProcesses(list)
End Sub

Private Sub KillProcesses(items As List(Of String))
    For Each item As String In items.Where(Function(listItem) listItem <> "//This Line") ' Exclude redundant text
        Dim processes = Process.GetProcessesByName(item)

        For Each process As Process In processes
            Try
                process.Kill()                         
            Catch
                ' Do your error handling here
            End Try
        Next
    Next
End Sub

更新:下面的代码是更新版本,以反映下面评论中要求的更改

Private Sub Question1()
    Dim list = File.ReadAllLines("YourFilePath").ToList()
    Dim itemCount = list.Count

    For i As Integer = 0 To itemCount - 1
        If list(i) = "//This Line" Then
            If (i + 1 > itemCount - 1) Then ' Check if the current item is the last one in the list, if it is then add the text to the list
                list.Add(TextBox1.Text)
            Else ' An item exists, so just update its value
                list(i + 1) = TextBox1.Text
            End If
        End If
    Next

    ' Write the list back to the file
    File.WriteAllLines(Application.StartupPath & "\test.txt", list)

    KillProcesses(list)
End Sub
于 2013-05-05T23:54:12.007 回答