Hayat Hasan
Hayat Hasan

Reputation: 229

Getting Access Denied Error while trying to remove specific lines from a text file

I'm getting error System.UnauthorizedAccessException: 'Access to the path '\File.txt' is denied.' when trying to delete a specific line from a text file, Codes in below. I'm very new in VB programming and was searching google for a way to delete specific lines and found several code snippet but most of them is giving the same error.

I thought the reason of this is because ReadAllLines is using the file while StreamWriter is trying to modify the file content. Can anyone please suggest a better way to perform the job.

#

Public Sub DeleteLineFromFile(ByVal Path As String, ByVal LineNumber As Integer)
    Dim lines() As String = IO.File.ReadAllLines(Path)
    Dim Count As Integer = 0
    Count = lines.Length

    If LineNumber <= Count Then
        lines.SetValue("", LineNumber - 1)
        Using sw As New IO.StreamWriter(Path)
            For Each Line As String In lines
                If Line <> "" Then
                    sw.WriteLine(Line)
                End If
            Next
        End Using        
    End If

    lines = Nothing
    Count = Nothing
End Sub

Upvotes: 1

Views: 88

Answers (1)

Hayat Hasan
Hayat Hasan

Reputation: 229

I tried another way and used a thought of deleting the file right before writing the file and it seems working. However any good suggestion would be highly appreciated since I'm a newbie in VB.

Sub RemoveAtLine(ByVal filePath As String, Optional ByVal lineRemove As Integer = -1)

    Dim lines As New List(Of String)(File.ReadAllLines(filePath))
    If (lineRemove >= 0 And lineRemove < lines.Count) Then
        lines.RemoveAt(lineRemove)
        File.Delete(filePath)
    End If

    File.WriteAllLines(filePath, lines.ToArray())

End Sub

Upvotes: 1

Related Questions