2013-08-01 37 views
0

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

 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 

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

+0

我会更像'var lines = IO.File.ReadAllLines(path); IO.File.WriteAllLines(path,lines.Except(deleteTheseLinesList));'where'deleteTheseLinesList'是你想要删除的行的列表。 – asawyer

+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