Deleting data from a file

G

Guest

Hi there,

I'm using the code below to try to delete a name from a list of names in a
file.

Unfortunately it doesn't quite do what I want it to.

Instead of looking for the name in the textbox and deleting that it is just
deleting the first line of data in the file.

It also writes that data back to the new file in a different format to how
it was originally ie instead of having the lines "jo bloggs, 094352678
john smith,094563728"
I get "jo bloggs, 094352678,john smith,094563728"

What must I adjust in this code to get it to do what I need (delete the name
that is shown in the textbox and display it in the file in the first way
shown above).

Cheers,

Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btndelete.Click
Dim message As String
If txtname.Text <> "" Then
If IO.File.Exists(TextBox1.Text) Then
deleteperson()
Else
message = "Either no file has yet been created or "
message = message & "the file cannot be found."
MsgBox(message, , "File not found.")
End If
End If
End Sub
Sub deleteperson()
Dim name, phoneno As String
Dim data() As String
Dim foundflag As Boolean = False
Dim sr As IO.StreamReader = IO.File.OpenText(TextBox1.Text)
Dim sw As IO.StreamWriter = IO.File.CreateText("temp.txt")
data = sr.ReadLine().Split(","c)
name = data(0)
phoneno = data(1)
Do While (sr.Peek <> -1)
name = sr.ReadLine
phoneno = sr.ReadLine
If (name <> txtname.Text) Then
Dim outputline() As String = {name, phoneno}
sw.WriteLine(Join(outputline, ","))
Else
foundflag = True
End If
Loop
sr.Close()
sw.Close()
IO.File.Delete(TextBox1.Text)
IO.File.Move("temp.txt", TextBox1.Text)
If Not foundflag Then
MsgBox("The name was not found.", , "")
Else
txtname.Clear()
End If
End Sub
 
C

Chris Dunaway

SiouxieQ wrote:
You have a few confusing things in your code:
data = sr.ReadLine().Split(","c)
name = data(0)
phoneno = data(1)

Here, you read a line from your file, split it apart based on a comma
and assign data(0) to name, and data(1) to phone.
Do While (sr.Peek <> -1)
name = sr.ReadLine
phoneno = sr.ReadLine

But right here inside the while loop, you discard those values and read
two more lines? What is the structure of the file? As Cor suggested,
if you do a ReadLine and then use the String.IndexOf method to search
for the name, that would probably produce cleaner code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top