VB.NET替换线和&任务杀手

时间:2013-05-05 22:58:53

标签: vb.net

我的VB.NET项目有两个问题,编码在.netFrameWork 4.0

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

例如: 在textfile1.txt

//This Line
Some Code here

我需要使用TextBox1.text

中的文本替换Some Code

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

例如: 在MultiLineTextBox1

notepad
mspain

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

1 个答案:

答案 0 :(得分: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