# Find and replace in a text file

• (4 Pages)
• 1
• 2
• 3
• Last »

## 49 Replies - 16677 Views - Last Post: 28 June 2011 - 01:44 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=234425&amp;s=b4322baee264dfa01ccdb4ba08b0a325&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 samuel17

Reputation: 2
• Posts: 209
• Joined: 14-October 10

# Find and replace in a text file

Posted 03 June 2011 - 07:57 AM

Hi All,
I am making a program for work, i have it partly coded, unfortunately i don't have a wifi connection for my laptop right now which makes it hard to add my code here. What i am trying to do is have the user pull in a text file from anywhere on the computer using a open file box that pops up, i got that part, to make sure that is working i have a textbox that reads the data of that text file, it gets pulled in fine using a stream reader. Now what i need to do is search the text file for certain values, and depending on the selected item in the listbox which is on another form, change that value in the text file, im guessing i will need to use a stream writer, and ive seen examples used based on the file location(C://....) but in my case im not sure how to do it. Any one have some good examples? i will paste in my code later when i get wifi.

Thanks,
Sam

Is This A Good Question/Topic? 0

## Replies To: Find and replace in a text file

### #2 Btu

Reputation: 36
• Posts: 248
• Joined: 16-May 11

## Re: Find and replace in a text file

Posted 03 June 2011 - 08:21 AM

Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText("I:\text.txt") 'or OpenText
writeFile.Close()



you can use a variable with your streamreader to find the location of a character or string with string.IndexOf which returns an integer value of the location.
You could pull the whole line with streamreaders readline(), search it for a value with string.IndexOf, string.InsertAt the Indexof location.
Some other coders might have a better idea, but that's probably how I would tackle it.

### #3 modi123_1

• Suitor #2

Reputation: 7634
• Posts: 27,892
• Joined: 12-June 08

## Re: Find and replace in a text file

Posted 03 June 2011 - 08:21 AM

What's the issue? It seems straight forward.

1. pick file location.
3. use string methods to do a 'replace' and/or 'find'.
4. use stream writer to save back to the file (or where ever).

### #4 samuel17

Reputation: 2
• Posts: 209
• Joined: 14-October 10

## Re: Find and replace in a text file

Posted 03 June 2011 - 08:33 AM

hi guys, thanks for both of your responses, sorry if i wasnt too clear, I dont know how to use the streamwriter since it isnt reading the file based on its location, most of the examples i seen it pulls the file in programmatically, like:
dim sw as new streamreader(C://.....)


im not looking at the example i had seen so that might not be exact, but since my file is being selected by the user using the OpenFileDialog() method, i dont know how to tell the streamwriter to save the file, and also do like a save as, i do not want it to overwrite the file as this will be a master file. I do use replace to find and replace what im looking for, but i cant verify it is working because i cant re-write the file and reload the data in the textbox to see if it changed, hope this is a better explanation of what im working on/with.

Thanks again,
Sam

### #5 modi123_1

• Suitor #2

Reputation: 7634
• Posts: 27,892
• Joined: 12-June 08

## Re: Find and replace in a text file

Posted 03 June 2011 - 08:46 AM

Quote

hi guys, thanks for both of your responses, sorry if i wasnt too clear, I dont know how to use the streamwriter since it isnt reading the file based on its location, most of the examples i seen it pulls the file in programmatically, like:
dim sw as new streamreader(C://.....)


where's this example from?

What could be more hard than:
Dim sr As StreamReader = New StreamReader("c:\myfile.txt")
Dim sFile As String = String.Empty

sr.Close()



Have you read the help file on the streamreader? I mean they are pretty exact. MSDN also has the exact information on streamwriter.

Quote

im not looking at the example i had seen so that might not be exact, but since my file is being selected by the user using the OpenFileDialog() method, i dont know how to tell the streamwriter to save the file,

The openfiledialog keeps the last selected path.. ah, use that? Hell when the OFD comes back you can take that string value and assign it to a global string value and use it when ever!

Quote

and also do like a save as, i do not want it to overwrite the file as this will be a master file.

the stream writer will write to what ever file name you pick. You decide how to select a new file name.

Quote

I do use replace to find and replace what im looking for, but i cant verify it is working because i cant re-write the file and reload the data in the textbox to see if it changed, hope this is a better explanation of what im working on/with.

Thanks again,
Sam

Have you learned how to debug an application? Putting a breakpoint somewhere and inspecting the values of the variables? If not then I suggest stopping now and spend time on this skill. It's something you will use day in and day out as you write code. Instead of squawking to be spoon fed answers you solve them yourself!
Debugging

### #6 samuel17

Reputation: 2
• Posts: 209
• Joined: 14-October 10

## Re: Find and replace in a text file

Posted 03 June 2011 - 09:04 AM

jeez man, im a rookie here, dont gotta be so harsh, ive been searching for the past 2 hours on this, im sorry for asking for help, thought thats what you guys were here for.

### #7 modi123_1

• Suitor #2

Reputation: 7634
• Posts: 27,892
• Joined: 12-June 08

## Re: Find and replace in a text file

Posted 03 June 2011 - 09:07 AM

Harsh maybe, but just laying it out there. I have no idea what your skill level is, so I have to cover all the critical things to learn. Where to find help files, how to debug, etc.

### #8 samuel17

Reputation: 2
• Posts: 209
• Joined: 14-October 10

## Re: Find and replace in a text file

Posted 03 June 2011 - 09:14 AM

ive been in a programming class for VB for 4 semesters, i have a relatively good knowledge, but one thing we never got into was reading/writing to text files, we had one small assignment on that my 2nd semester, not enough for me to learn much about it. Im no VB genius, not even close, thats why i need help, i understand debugging, and variables, quite a few form controls, assigning varibles with values, yada yada, i looked on MSDN for help but all the things i found did not refer to opening the file using the opendialog so this is where i turned, especially cuz ive never done much with text files, nor does it help that im self taught(google and books) because of lack of instructor help ever, im doin my best here man, i do appreciate the help.

Sam

### #9 modi123_1

• Suitor #2

Reputation: 7634
• Posts: 27,892
• Joined: 12-June 08

## Re: Find and replace in a text file

Posted 03 June 2011 - 09:24 AM

Quote

i looked on MSDN for help but all the things i found did not refer to opening the file using the opendialog

Well yeah - MSDN shows you the base operations for each control - it's your job to make the lego blocks fit together. Think of all the permuations of "OFD plus...." there are. Grids, buttons, labels, etc. They can't show you all those together so you must sit down, write out where you want to go, and then look at the members and methods available for each of the major components.

Streamreader requires a string path for a file name. Check. I need a string then!
OFD has a "file name" property that "Gets or sets a string containing the file name selected in the file dialog box". Sweet!

see that sort of figuring out the pieces of the puzzle is what makes you a programmer. I've seen enough people gimp through just googling the components, but to actually put the rubber to the road is where the magic happens.

It sounds like you have been exposed to a significant amount of VB - I mean four semesters is a long time. Time to switch from being a passive consumer and be active! It makes you a better developer, builds confidence, and helps you build more complex programs!

### #10 samuel17

Reputation: 2
• Posts: 209
• Joined: 14-October 10

## Re: Find and replace in a text file

Posted 03 June 2011 - 09:30 AM

Another thing quick if i may ask, i never thought of using the same path that the opendialog holds, is there a way to get the file name only from that? in this case the file name would be "P00790.M13" and i want it to save, depending on the selection from the other forms listbox, with that extension, so depending on that selection it could be saved with an extension M(3-28). I guess what im asking, how do i get the file name but without all the location part, just the file name itself. Can i somehow set that to a variable and use that variable in the location such as:
Using outfile As New StreamWriter(mydocpath & "\AllTxtFiles.txt")
outfile.Write(sb.ToString())
End Using



which is straight from MSDN, but where it says "AllTxtFiles" have a variable FileName and be "FileName.txt", my other thought as im writing this is, can i have a variable to the ".txt" part because that also depends on the listbox selection as i had stated. Again i appreciate the help, it's nice to have people to bounce stuff off of. This program im doing is going to be very complex, i am barely scratching the surface yet, but getting this start i should then be able to build on it. I do pretty good to put the legos together, i made it through 4 semesters with little to no instructor help sometimes i just need a push and a little advice.

Thanks,
Sam

This post has been edited by samuel17: 03 June 2011 - 09:33 AM

### #11 modi123_1

• Suitor #2

Reputation: 7634
• Posts: 27,892
• Joined: 12-June 08

## Re: Find and replace in a text file

Posted 03 June 2011 - 09:39 AM

Quote

Another thing quick if i may ask, i never thought of using the same path that the opendialog holds, is there a way to get the file name only from that? in this case the file name would be "P00790.M13" and i want it to save, depending on the selection from the other forms listbox, with that extension, so depending on that selection it could be saved with an extension M(3-28). I guess what im asking, how do i get the file name but without all the location part, just the file name itself.

check the method "GetFileName" In the System.Io.Path namespace. You can also get the extension, path, and a plethora of other information.
http://msdn.microsof...em.io.path.aspx

Quote

Can i somehow set that to a variable and use that variable in the location such as:

yes

Quote

which is straight from MSDN, but where it says "AllTxtFiles" have a variable FileName and be "FileName.txt", my other thought as im writing this is, can i have a variable to the ".txt" part because that also depends on the listbox selection as i had stated.

See see above

### #12 samuel17

Reputation: 2
• Posts: 209
• Joined: 14-October 10

## Re: Find and replace in a text file

Posted 03 June 2011 - 09:42 AM

oooo that is some good stuff right there, pretty much a gold mine! Thanks modi! im done here for awhile, till i get further into this and need someone to bounce more stuff off of. Thank you again.

Sam

### #13 Btu

Reputation: 36
• Posts: 248
• Joined: 16-May 11

## Re: Find and replace in a text file

Posted 03 June 2011 - 10:47 AM

samuel17, on 03 June 2011 - 09:14 AM, said:

ive been in a programming class for VB for 4 semesters, i have a relatively good knowledge, but one thing we never got into was reading/writing to text files, we had one small assignment on that my 2nd semester, not enough for me to learn much about it. Im no VB genius, not even close, thats why i need help, i understand debugging, and variables, quite a few form controls, assigning varibles with values, yada yada, i looked on MSDN for help but all the things i found did not refer to opening the file using the opendialog so this is where i turned, especially cuz ive never done much with text files, nor does it help that im self taught(google and books) because of lack of instructor help ever, im doin my best here man, i do appreciate the help.

Sam

I know this is off topic, but in second semester we did in depth input output to text files. If you haven't seen streamreader in 4 semesters, I'm very very shocked.

### #14 samuel17

Reputation: 2
• Posts: 209
• Joined: 14-October 10

## Re: Find and replace in a text file

Posted 03 June 2011 - 01:55 PM

hi Btu,
I know it is pretty sad, but i figure seeing as how when i tried to ask even the simpliest question to the instructor i always was told "I can't give you the answer", i started being not surprised by anything, not sure what he gets paid for. Even if i asked "would this be the correct method to use for something like this", which i did often in my first semester when i was diving head first trying to learn this, id get that response, so sad as it is, it is what it is, it's why i became a DIC, get some help from people who know stuff How i made it through 4 semesters i dont know, i did make the best texas hold em game out of the whole class.....of 4 people haha I'm still learning and appreciate everyones help and patience.

Sam

### #15 samuel17

Reputation: 2
• Posts: 209
• Joined: 14-October 10

## Re: Find and replace in a text file

Posted 03 June 2011 - 02:14 PM

Back on topic, as i had mentioned i would do, here is my code i have so far, it is not done so i do have some loose ends and stuff i am still planning on using and doing with so dont hurt me yet for bad code My code for the main form, just reads the file, puts it in a textbox, has some properties of the file, a few buttons:
Option Strict Off
Imports System.Object
Imports System.MarshalByRefObject
Imports System.ComponentModel.Component
Imports System.Windows.Forms.CommonDialog
Imports System.Windows.Forms.FileDialog
Imports System.Windows.Forms.OpenFileDialog
Imports System.IO

Public Class SelectForm
Dim number As Integer
Public theFile As String
Public fileName As String
Public filePath As String

Private Sub OpenFileBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OpenFileBtn.Click
Dim openFile As New OpenFileDialog()

openFile.Title = "Select Text File"
openFile.ShowDialog()
FileTextBox.Text = theFile
sr.Close()
sourceLbl.Text = openFile.FileName
sizeLbl.Text = CStr(FileLen(openFile.FileName)) & " Bytes"
LastModLbl.Text = CStr(FileDateTime(openFile.FileName))
filePath = openFile.FileName
fileName = Path.GetFileName(filePath)

End Sub

Private Sub MachineSelectBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MachineSelectBtn.Click
MachineSelection.Show()
Me.Hide()
End Sub
End Class



My form that has the listbox that is used to select a machine:
Imports System.IO

Public Class MachineSelection

Private Sub MachineSelection_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub

Private Sub MachineListBox_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MachineListBox.DoubleClick
Dim response As MsgBoxResult
Dim title As String
Dim style As MsgBoxStyle
Dim msg As String
Dim machineSelected As String
Dim fileExtension As String

machineSelected = MachineListBox.SelectedItem.ToString
SelectForm.MachineLbl.Text = machineSelected
fileExtension = machineSelected.Replace("C", "")
msg = "Do you really want to change program to reflect " & machineSelected & "?"
style = MsgBoxStyle.YesNo
title = "Machine Conformation"
response = MsgBox(msg, style, title)
If response = MsgBoxResult.Yes Then
Me.Close()
SelectForm.Show()
Else

End If
If MachineListBox.SelectedItem.ToString <> "MC13" Or MachineListBox.SelectedItem.ToString <> "MC15" Or _
MachineListBox.SelectedItem.ToString <> "MC21" Then
SelectForm.theFile.Replace("M03", "M13")
Else
SelectForm.theFile.Replace("M13", "M03")
End If

End Sub
End Class


If you see anything i could do to make this more effient let me know, thats another thing i didnt really learn in class, it was pretty much just make it work

Thanks,
Sam