Results 1 to 26 of 26

Thread: Reading contents of a text file [RESOLVED]

  1. #1

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575

    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:
    1. Dim fileSettings As Short
    2.         fileSettings = FreeFile()
    3.         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.

  2. #2
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    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:
    1. Imports System.IO

    VB Code:
    1. If File.Exists("C:\samplexml.txt") Then
    2.  
    3.  
    4.             Dim s As New IO.StreamReader("C:\samplexml.txt", System.Text.Encoding.ASCII)
    5.  
    6.             s.ReadLine() 'reads 1 line
    7.             s.ReadLine() 'reads 1 line
    8.             s.ReadLine() 'reads 1 line
    9.  
    10.             'now get fourth line, assign to string
    11.             Dim c As String = s.ReadLine
    12.             MessageBox.Show(c)
    13.             s.Close()
    14.         End If

    You should digest the following 2-page example article:

    http://www.vbwm.com/articles/builder...p?ArticleID=15

  3. #3

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    Thanks very much! That works great

  4. #4

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    Oh, I just remembered.

    How about editing those specific lines to equal something else?

    Thanks

  5. #5
    Lively Member
    Join Date
    Aug 2003
    Location
    When?!?!
    Posts
    108
    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."

  6. #6
    Frenzied Member Mike Hildner's Avatar
    Join Date
    Jul 2002
    Location
    Des Moines, NM
    Posts
    1,690
    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

  7. #7
    Frenzied Member <ABX's Avatar
    Join Date
    Jul 2002
    Location
    Canada eh...
    Posts
    1,622
    this what you wanted or did you want to replace the whole line?

    VB Code:
    1. 'requires System.IO
    2.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    3.         Dim strFile As String = InputBox("FilePath?")
    4.         Dim strSearch As String = InputBox("Search String?")
    5.         Dim strReplace As String = InputBox("Replace String?")
    6.  
    7.         FileSearch(strFile, strSearch, strReplace)
    8.     End Sub
    9.  
    10.     Public Function FileSearch(ByVal strFilePath As String, ByVal strSearch As String, ByVal strReplace As String)
    11.         Dim strArray() As String = LoadFileToArray(strFilePath)
    12.         Dim retVal As Integer = SearchAndReplaceArray(strSearch, strReplace, strArray)
    13.         WriteArrayToFile(strFilePath, strArray)
    14.  
    15.         MsgBox(retVal & " lines contained '" & strSearch & "'!")
    16.     End Function
    17.  
    18.     Private Function LoadFileToArray(ByVal strFilePath As String) As String()
    19.         Dim sr As New StreamReader(strFilePath)
    20.  
    21.         Dim strLines() As String = Split(sr.ReadToEnd, vbCrLf)
    22.  
    23.         sr.Close()
    24.  
    25.         Return strLines
    26.     End Function
    27.  
    28.     Private Function WriteArrayToFile(ByVal strFilePath As String, ByVal strArray() As String)
    29.         Dim sw As New StreamWriter(strFilePath)
    30.  
    31.         Dim I As Integer
    32.  
    33.         For I = 0 To strArray.GetUpperBound(0)
    34.             sw.Write(strArray(I) & vbCrLf)
    35.         Next
    36.  
    37.         sw.Close()
    38.     End Function
    39.  
    40.     Private Function SearchAndReplaceArray(ByVal strSearchFor As String, ByVal strReplaceWith As String, ByRef strArray() As String) As Integer ' Returns how many changed
    41.         Dim intChanged As Integer
    42.         Dim I As Integer
    43.  
    44.         For I = 0 To strArray.GetUpperBound(0)
    45.             If InStr(strArray(I), strSearchFor, CompareMethod.Text) <> 0 Then 'Match
    46.                 strArray(I) = Replace(strArray(I), strSearchFor, strReplaceWith)
    47.                 I += 1
    48.             End If
    49.         Next
    50.     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

  8. #8

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    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

  9. #9

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    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.

  10. #10

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    Originally posted by <ABX
    [B]this what you wanted or did you want to replace the whole line?

    VB Code:
    1. 'requires System.IO
    2.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    3.         Dim strFile As String = InputBox("FilePath?")
    4.         Dim strSearch As String = InputBox("Search String?")
    5.         Dim strReplace As String = InputBox("Replace String?")
    6.  
    7.         FileSearch(strFile, strSearch, strReplace)
    8.     End Sub
    9. ...
    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

  11. #11
    Frenzied Member <ABX's Avatar
    Join Date
    Jul 2002
    Location
    Canada eh...
    Posts
    1,622
    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:
    1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    2.         Dim strFile As String = InputBox("FilePath?")
    3.         Dim strSearch As String = InputBox("Search String?")
    4.         Dim strReplace As String = InputBox("Replace String?")
    5.  
    6.         FileSearch(strFile, strSearch, strReplace)
    7.     End Sub
    8.  
    9.     Public Function FileSearch(ByVal strFilePath As String, ByVal strSearch As String, ByVal strReplace As String)
    10.         Dim strArray() As String = LoadFileToArray(strFilePath)
    11.         Dim retVal As Integer = SearchAndLineReplaceArray(strSearch, strReplace, strArray)
    12.         WriteArrayToFile(strFilePath, strArray)
    13.  
    14.         MsgBox(retVal & " lines contained '" & strSearch & "'!")
    15.     End Function
    16.  
    17.     Private Function LoadFileToArray(ByVal strFilePath As String) As String()
    18.         Dim sr As New StreamReader(strFilePath)
    19.  
    20.         Dim strLines() As String = Split(sr.ReadToEnd, vbCrLf)
    21.  
    22.         sr.Close()
    23.  
    24.         Return strLines
    25.     End Function
    26.  
    27.     Private Function WriteArrayToFile(ByVal strFilePath As String, ByVal strArray() As String)
    28.         Dim sw As New StreamWriter(strFilePath)
    29.  
    30.         Dim I As Integer
    31.  
    32.         For I = 0 To strArray.GetUpperBound(0)
    33.             sw.Write(strArray(I) & vbCrLf)
    34.         Next
    35.  
    36.         sw.Close()
    37.     End Function
    38.  
    39.     Private Function SearchAndLineReplaceArray(ByVal strSearchFor As String, ByVal strReplaceWith As String, ByRef strArray() As String) As Integer ' Returns how many changed
    40.         Dim intChanged As Integer
    41.         Dim I As Integer
    42.  
    43.         For I = 0 To strArray.GetUpperBound(0)
    44.             If InStr(strArray(I), strSearchFor, CompareMethod.Text) <> 0 Then 'Match
    45.                 strArray(I) = strReplaceWith 'Replacing the whole line is easier :D
    46.                 I += 1
    47.             End If
    48.         Next
    49.     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

  12. #12

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    thanks, ill try it later

  13. #13

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    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.

  14. #14
    Frenzied Member Memnoch1207's Avatar
    Join Date
    Feb 2002
    Location
    DUH, Guess...Hint: It's really hot!
    Posts
    1,861
    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

  15. #15

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    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!

  16. #16
    Frenzied Member Memnoch1207's Avatar
    Join Date
    Feb 2002
    Location
    DUH, Guess...Hint: It's really hot!
    Posts
    1,861
    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

  17. #17

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    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

  18. #18

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    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...

  19. #19
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    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.

  20. #20
    Frenzied Member Mike Hildner's Avatar
    Join Date
    Jul 2002
    Location
    Des Moines, NM
    Posts
    1,690
    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

  21. #21
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    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.

  22. #22

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    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

  23. #23

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    no ideas? Maybe there is some code which will remove extra lines at the end of a file I can use?

    Thanks

  24. #24
    Frenzied Member <ABX's Avatar
    Join Date
    Jul 2002
    Location
    Canada eh...
    Posts
    1,622
    Sorry for slow responce, dont have Internet during the week

    VB Code:
    1. Private Function WriteArrayToFile(ByVal strFilePath As String, ByVal strArray() As String)
    2.         Dim sw As New StreamWriter(strFilePath)
    3.  
    4.         Dim I As Integer
    5.  
    6.         For I = 0 To strArray.GetUpperBound(0)
    7.             'Fixed extra vbCrLF :D
    8.             sw.Write(IIf(strArray.GetUpperBound(0) <> I, strArray(I) & vbCrLf, strArray(I)))
    9.  
    10.         Next
    11.  
    12.         sw.Close()
    13.     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

  25. #25
    Frenzied Member Mike Hildner's Avatar
    Join Date
    Jul 2002
    Location
    Des Moines, NM
    Posts
    1,690
    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

  26. #26

    Thread Starter
    Fanatic Member LITHIA's Avatar
    Join Date
    Dec 2002
    Location
    UK, England
    Posts
    575
    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
  •  



Click Here to Expand Forum to Full Width