WPF Vb.net删除特定行错误

时间:2013-08-01 18:38:23

标签: .net vb.net streamreader streamwriter

当我运行以下代码(在一个事件中)删除字符串“DoNotShowSafeBootPages = Yes”时,我收到此错误“进程无法访问文件'C:\ cfig.ini',因为它正被另一个人使用过程“。

     Sub DeleteLineSM()
    Dim line As String = Nothing
    Dim line_to_delete As String = "DoNotShowSafeBootPage=Yes"

    Using reader As New StreamReader("C:\cfig.ini")
        Using writer As New StreamWriter("C:\cfig.ini")
            While (reader.ReadLine()) IsNot Nothing
                If [String].Compare(line, line_to_delete) = 0 Then
                    Continue While
                End If

                writer.WriteLine(line)
            End While
        End Using
    End Using
End Sub

我要做的就是从文本文件中删除上面提到的字符串。有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

Sub DeleteLineSM()
 Dim lines As New List(Of String)
 Dim line_to_delete As String = "DoNotShowSafeBootPage=Yes"
 Using reader As New StreamReader("C:\cfig.ini")
    'need a looping mechanism
   While Not reader.EndOfStream
      'add to our list
     lines.Add(reader.Readline)
   End While
 End Using 
  'check if the delete text exist and then delete it
 If lines.Contains(line_to_delete) Then lines.Remove(line_to_delete)
  'overwrite the file
 Using writer As New StreamWriter("C:\cfig.ini")
    For Each line In Lines
     writer.WriteLine(line)
    Next
 End Using
End Sub