|
-
Nov 22nd, 2003, 06:29 AM
#1
Thread Starter
Fanatic Member
Reading contents of a text file [RESOLVED]
Hi,
How would you open a text file and read a certain line of it?
Eg. 1) Read the contents of Line 4 and if it is equal to something, then execute some code.
2) If its equal to something else, exeucte some other code.
3) If its not equal to either, produce an error message box saying invalid.
Any ideas? Thanks
Current I have:
VB Code:
Dim fileSettings As Short
fileSettings = FreeFile()
FileOpen(fileSettings, VB6.GetPath & "\SMSettings.ini", OpenMode.Input)
It works fine and I have put Error Handlers to it so the program wont crash it if doesnt exist.
Last edited by LITHIA; Nov 28th, 2003 at 10:41 AM.
-
Nov 22nd, 2003, 08:43 AM
#2
I wonder how many charact
First, move away from FileOpen, its an antiquated method that exists soley for people upgrading from VB6.
For just reading a text file in .Net, use StreamReader.ReadLine
VB Code:
If File.Exists("C:\samplexml.txt") Then
Dim s As New IO.StreamReader("C:\samplexml.txt", System.Text.Encoding.ASCII)
s.ReadLine() 'reads 1 line
s.ReadLine() 'reads 1 line
s.ReadLine() 'reads 1 line
'now get fourth line, assign to string
Dim c As String = s.ReadLine
MessageBox.Show(c)
s.Close()
End If
You should digest the following 2-page example article:
http://www.vbwm.com/articles/builder...p?ArticleID=15
-
Nov 22nd, 2003, 02:01 PM
#3
Thread Starter
Fanatic Member
Thanks very much! That works great
-
Nov 22nd, 2003, 02:18 PM
#4
Thread Starter
Fanatic Member
Oh, I just remembered.
How about editing those specific lines to equal something else?
Thanks
-
Nov 22nd, 2003, 03:05 PM
#5
Lively Member
thats gonna take alot of coding. what you just said in that one simple sentance means:
a. Set the editing cursor to find the line to edit.
b. some kind of genious code to replace that line without deleting c:\
c. your wife or girlfriend will complain you spend too much time on the comp.
hope that helps.
DannyJoumaa
Advanced VB6 Programmer
Intermediate-Advanced VB .NET Programmer
Intermediate C# Programmer
Intermediate Win32 Developer
Beginner Mac OS X Developer
Contact: [email protected]
Favorite Sayings:
"Every time you open your mouth, you prove your an idiot."
"God is a programmer. Satan is a bug. Life is debugging."
-
Nov 22nd, 2003, 03:57 PM
#6
Frenzied Member
Umm, I gotta ask, what do you really want to do? Are you reading in the contents of an initialization file for your app? And then wanting to write back changed values?
Or do you just want to modify the fourth line of any text file?
Mike
-
Nov 22nd, 2003, 10:46 PM
#7
this what you wanted or did you want to replace the whole line?
VB Code:
'requires System.IO
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strFile As String = InputBox("FilePath?")
Dim strSearch As String = InputBox("Search String?")
Dim strReplace As String = InputBox("Replace String?")
FileSearch(strFile, strSearch, strReplace)
End Sub
Public Function FileSearch(ByVal strFilePath As String, ByVal strSearch As String, ByVal strReplace As String)
Dim strArray() As String = LoadFileToArray(strFilePath)
Dim retVal As Integer = SearchAndReplaceArray(strSearch, strReplace, strArray)
WriteArrayToFile(strFilePath, strArray)
MsgBox(retVal & " lines contained '" & strSearch & "'!")
End Function
Private Function LoadFileToArray(ByVal strFilePath As String) As String()
Dim sr As New StreamReader(strFilePath)
Dim strLines() As String = Split(sr.ReadToEnd, vbCrLf)
sr.Close()
Return strLines
End Function
Private Function WriteArrayToFile(ByVal strFilePath As String, ByVal strArray() As String)
Dim sw As New StreamWriter(strFilePath)
Dim I As Integer
For I = 0 To strArray.GetUpperBound(0)
sw.Write(strArray(I) & vbCrLf)
Next
sw.Close()
End Function
Private Function SearchAndReplaceArray(ByVal strSearchFor As String, ByVal strReplaceWith As String, ByRef strArray() As String) As Integer ' Returns how many changed
Dim intChanged As Integer
Dim I As Integer
For I = 0 To strArray.GetUpperBound(0)
If InStr(strArray(I), strSearchFor, CompareMethod.Text) <> 0 Then 'Match
strArray(I) = Replace(strArray(I), strSearchFor, strReplaceWith)
I += 1
End If
Next
End Function
Tips:
- Google is your friend! Search before posting!
- Name your thread appropriately... "I Need Help" doesn't cut it!
- Always post your code!!!! We can't read your mind!!! (well, at least most of us!)
- Allways Include the Name and Line of the Exception (if one is occuring!)
- If it is relevant state the version of Visual Studio/.Net Framwork you are using (2002/2003/2005)
If you think I was helpful, rate my post  IRC Contact: Rizon/xous ChakraNET/xous Freenode/xous
-
Nov 23rd, 2003, 07:22 AM
#8
Thread Starter
Fanatic Member
Does it really need all that fancy code? 
All I want is something simple. Exactly the same as how it reads the 5th line, but instead of reading it, it changes it to something else.
Not part of the line, all of it.
My file is a settings file, on the 5th line it says: "LoadOnStartup = 1" and i have done the code to detect if that is equal to 1 then a checkbox is checked on a form, if its 0 then the checkbox aint.
Now all I need is when you check a box or uncheck it, and press ok on the form, it will edit the line to what it needs.
I could do it by remaking the whole file easily with the Print function, as I only have 2 options in my program at the minute. But if say I put another 2 or 3 options on, I would start getting alot of different combinations of what can be in text file, so thats what I cant do.
So I need to replace a specific line in a text file with something else.
If the user checks a box, the 5th line will equal "LoadOnStartup = 1" If the user unchecks the box, the 5th line will equal "LoadOnStartup = 0" Understand?
Thanks
-
Nov 23rd, 2003, 07:25 AM
#9
Thread Starter
Fanatic Member
Originally posted by Danny J
thats gonna take alot of coding. what you just said in that one simple sentance means:
a. Set the editing cursor to find the line to edit.
b. some kind of genious code to replace that line without deleting c:\
c. your wife or girlfriend will complain you spend too much time on the comp.
hope that helps.
a - seems ok enough, i need some code like i have to read the line above.
b - I have no idea what you'r on about. "without deleting C:\" Sorry?? This is a text file
c - I am 14 years old, I don't have that problem and even if i did, I would tell them to let me do what I want.
-
Nov 23rd, 2003, 07:27 AM
#10
Thread Starter
Fanatic Member
Originally posted by <ABX
[B]this what you wanted or did you want to replace the whole line?
VB Code:
'requires System.IO
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strFile As String = InputBox("FilePath?")
Dim strSearch As String = InputBox("Search String?")
Dim strReplace As String = InputBox("Replace String?")
FileSearch(strFile, strSearch, strReplace)
End Sub
...
Thanks for that, I really appreciate it and I don't want to sound ungreatful for your hard work, but I don't think thats going to help me. But the Search part will! I can use the search bit for something else - thanks
-
Nov 23rd, 2003, 01:12 PM
#11
This code replaces the whole line not just the search string in the line and sorry this is about as simple as its going to get, you could put everything into 1 function but this way the code is more reuseable elsewhere in your project.
btw: the code took me >5 min to code so dont worry about it
VB Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strFile As String = InputBox("FilePath?")
Dim strSearch As String = InputBox("Search String?")
Dim strReplace As String = InputBox("Replace String?")
FileSearch(strFile, strSearch, strReplace)
End Sub
Public Function FileSearch(ByVal strFilePath As String, ByVal strSearch As String, ByVal strReplace As String)
Dim strArray() As String = LoadFileToArray(strFilePath)
Dim retVal As Integer = SearchAndLineReplaceArray(strSearch, strReplace, strArray)
WriteArrayToFile(strFilePath, strArray)
MsgBox(retVal & " lines contained '" & strSearch & "'!")
End Function
Private Function LoadFileToArray(ByVal strFilePath As String) As String()
Dim sr As New StreamReader(strFilePath)
Dim strLines() As String = Split(sr.ReadToEnd, vbCrLf)
sr.Close()
Return strLines
End Function
Private Function WriteArrayToFile(ByVal strFilePath As String, ByVal strArray() As String)
Dim sw As New StreamWriter(strFilePath)
Dim I As Integer
For I = 0 To strArray.GetUpperBound(0)
sw.Write(strArray(I) & vbCrLf)
Next
sw.Close()
End Function
Private Function SearchAndLineReplaceArray(ByVal strSearchFor As String, ByVal strReplaceWith As String, ByRef strArray() As String) As Integer ' Returns how many changed
Dim intChanged As Integer
Dim I As Integer
For I = 0 To strArray.GetUpperBound(0)
If InStr(strArray(I), strSearchFor, CompareMethod.Text) <> 0 Then 'Match
strArray(I) = strReplaceWith 'Replacing the whole line is easier :D
I += 1
End If
Next
End Function
Tips:
- Google is your friend! Search before posting!
- Name your thread appropriately... "I Need Help" doesn't cut it!
- Always post your code!!!! We can't read your mind!!! (well, at least most of us!)
- Allways Include the Name and Line of the Exception (if one is occuring!)
- If it is relevant state the version of Visual Studio/.Net Framwork you are using (2002/2003/2005)
If you think I was helpful, rate my post  IRC Contact: Rizon/xous ChakraNET/xous Freenode/xous
-
Nov 24th, 2003, 04:23 AM
#12
Thread Starter
Fanatic Member
-
Nov 24th, 2003, 11:12 AM
#13
Thread Starter
Fanatic Member
Thanks very much, the code works great. But I do have quite a big problem with it.
Whenever the file gets altered, an extra line gets added to the end of the file (blank with no characters) but still makes the file size larger than what it should be. This small file size change makes my program detect it as being changed outside the program. (some code I made to prevent invalid alterations by users)
Is there a way to modify the code to prevent it from keep adding the empty lines at the end? (i think u wud call it vbCrLf)
Thanks very much.
-
Nov 24th, 2003, 11:30 AM
#14
Frenzied Member
when you write the array to the file you are appending a vbcrlf to the end of each line
Code:
For I = 0 To strArray.GetUpperBound(0)
sw.Write(strArray(I) & vbCrLf)
Next
You'll need to do an if statement to determine if the line being written is the last array item...something like this
Code:
For I = 0 To strArray.GetUpperBound(0)
If(strArray(I) <> strArray.GetUpperBound(0)) Then
sw.Write(strArray(I) & vbCrLf)
Else
sw.Write(strArray(I))
End If
Next
Being educated does not make you intelligent.
Need a weekend getaway??? Come Visit
-
Nov 24th, 2003, 12:13 PM
#15
Thread Starter
Fanatic Member
Thanks - i understand what the codes doing now.
If I put "sw.Write(strArray(I))" without anything else, it makes the file completely blank apart from the line its just 'edited'
The only problem is when i use your method, I get an error when it trys doing this line:
If(strArray(I) <> strArray.GetUpperBound(0)) Then
An unhandled exception of type 'System.InvalidCastException' occurred in microsoft.visualbasic.dll
Additional information: Cast from string "// Important! Do not delete, mov" to type 'Double' is not valid.
"// Important! Do not delete, mov" is part of the top line of the file.
Any idea's why I am getting this problem and how to fix it? Thanks!
-
Nov 24th, 2003, 12:17 PM
#16
Frenzied Member
try changing
Code:
If(strArray(I) <> strArray.GetUpperBound(0)) Then
To
If(strArray(I) <> Convert.ToDouble(strArray.GetUpperBound(0))) Then
Being educated does not make you intelligent.
Need a weekend getaway??? Come Visit
-
Nov 24th, 2003, 12:20 PM
#17
Thread Starter
Fanatic Member
nope sorry 
No different, but remember it does say "to type 'Double' is not valid." so maybe that means a Double won't work in it?
I don't even know what a Double is so sorry If i am totally wrong. heh
-
Nov 24th, 2003, 12:31 PM
#18
Thread Starter
Fanatic Member
I did
If (strArray(I) <> Convert.ToString(strArray.GetUpperBound(0))) Then
and it worked, but i still get the extra line at the end which increases the file size...
-
Nov 25th, 2003, 11:45 AM
#19
As a side note XML or config files are .NETs replacement for the Ini file. Converting to xml/config would make life a lot easier and I'd recommend it. If there isn't an application which you didn't write that needs to read the INI file then I'd definately say convert it. If you aren't familiar with XML don't worry its not hard or if you need help switching it from the INI to XML then just post the INI file.
-
Nov 25th, 2003, 06:14 PM
#20
Frenzied Member
Further up this thread I asked if this was for a config file for your app, because I was going to recommend the same thing - use xml.
But, I'm not sure if I have down a good method. I've been creating a "properties" object (an instance of a class) that has all my config stuff, then serializing/deserializing to xml.
Is there a better/more accepted way?
TIA,
Mike
-
Nov 25th, 2003, 06:33 PM
#21
There is nothing wrong with serializing. Its more a matter of preference. The .NET Framework has a set of objects defined to read from the AppSettings part of an app.config file in the System.Configuration namespace. Although I usually use my own since there is no native writer just reader. Other ways are to just use an XMLDocument or Dataset for the config I/O. Whatever works for you, but they are all better than storing just text since XML is far easier to read/write and parse.
-
Nov 26th, 2003, 05:05 AM
#22
Thread Starter
Fanatic Member
ive wrote so much code tho for this and its working great apart from the extra lines at the end!
Please can you help me fix this, and then in future progs i can use xml - thanks
-
Nov 27th, 2003, 11:31 AM
#23
Thread Starter
Fanatic Member
no ideas? Maybe there is some code which will remove extra lines at the end of a file I can use?
Thanks
-
Nov 27th, 2003, 07:13 PM
#24
Sorry for slow responce, dont have Internet during the week 
VB Code:
Private Function WriteArrayToFile(ByVal strFilePath As String, ByVal strArray() As String)
Dim sw As New StreamWriter(strFilePath)
Dim I As Integer
For I = 0 To strArray.GetUpperBound(0)
'Fixed extra vbCrLF :D
sw.Write(IIf(strArray.GetUpperBound(0) <> I, strArray(I) & vbCrLf, strArray(I)))
Next
sw.Close()
End Function
Tips:
- Google is your friend! Search before posting!
- Name your thread appropriately... "I Need Help" doesn't cut it!
- Always post your code!!!! We can't read your mind!!! (well, at least most of us!)
- Allways Include the Name and Line of the Exception (if one is occuring!)
- If it is relevant state the version of Visual Studio/.Net Framwork you are using (2002/2003/2005)
If you think I was helpful, rate my post  IRC Contact: Rizon/xous ChakraNET/xous Freenode/xous
-
Nov 27th, 2003, 11:42 PM
#25
Frenzied Member
LITHIA,
I respect your resolve, but, IMHO, refactoring can be a beautiful thing.
Take the knowledge you've learned with you and move on - start deleting lines of code.
In the end, your app will be easier to read and maintain, smaller and more effecient.
In economics, what you describe is a "sunk cost" - you've expended resources that you cannot reclaim. That is not a valid reason to continue a particular pursuit when you know that there are better options. Throw away your old code and chalk it up to learning.
Apologies for the unsolicited opinion. Feel free to disregard. I believe you said somewhere else that you were quite young, and as someone that hires programmers, I'm only explaining a quality that I look for.
Off my soap box now - code on and have fun!
Mike
-
Nov 28th, 2003, 10:40 AM
#26
Thread Starter
Fanatic Member
wow <ABX thanks so much!! It works great now, I cant say how much I appreciate the correction!
Also, Mike Hildner, I really appreciate your inspiration in what you said. It is very much something I should not ignore. I will make sure to do as you say in further projects of mine, but right now in this project I wanted to use this method, thats why I didnt change.
Thanks very much to everyone who helped, I wouldn't have been able to do it without ya!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|