Results 1 to 5 of 5

Thread: Taking a variable from a file

  1. #1

    Thread Starter
    Member SeMcDun's Avatar
    Join Date
    May 2007
    Location
    Scotland
    Posts
    47

    Taking a variable from a file

    Can anyone help me?

    I'm making a text-based game and wish to save all the details onto a file named PlayerInfo.ini

    That's not the problem yet, just now I am concentrating on taking a variable from a file.

    Hope you can help, thanks.

  2. #2
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,950

    Re: Taking a variable from a file

    So you just want to read a string from a file right?
    Code:
        Private Function ReadStringFromFile(ByVal inputfilename As String) As String
            Dim r As New System.IO.StreamReader(inputfilename)
            Dim MyVar As String = String.Empty
            If r.Peek <> -1 Then MyVar = CStr(r.ReadLine)
            r.Close()
            Return MyVar
        End Function
    Use the same approach for other types such as booleans, integers etc.

  3. #3

    Thread Starter
    Member SeMcDun's Avatar
    Join Date
    May 2007
    Location
    Scotland
    Posts
    47

    Re: Taking a variable from a file

    Thanks, so does this work for more than one line in a file?

    example

    PlayerName = SeMcDun
    PlayerLv = 1

    I could take just "SeMcDun" or just "1" right?

    also.. if you could be bothered, would you be able to write what each line does, for future references so i can learn why I am doing this.

  4. #4
    Frenzied Member
    Join Date
    Jun 2005
    Posts
    1,950

    Re: Taking a variable from a file

    If you have one string per line then you could do this;

    Code:
        Dim MyValues As String() = ReadStringsFromFile("YourFileName")
        'First string is MyValues(0) 
        'Last  string is MyValues(MyValues.GetUpperBound(0))
    
        Private Function ReadStringsFromFile(ByVal inputfilename As String) As String()
            'Read all lines as an array of strings
            Dim strings As String() = IO.File.ReadAllLines(inputfilename)
            'Trim any leading/trailing spaces off of each string in the array
            For i As Integer = 0 To strings.GetUpperBound(0)
                strings(i) = strings(i).Trim
            Next
            Return strings
        End Function
    Last edited by Bulldog; May 10th, 2007 at 04:53 PM.

  5. #5

    Thread Starter
    Member SeMcDun's Avatar
    Join Date
    May 2007
    Location
    Scotland
    Posts
    47

    Re: Taking a variable from a file

    Thanks again! I'm beginning to understand why I put stuff where. Pretty self-explanatory huh?

    Well yeh, thanks and you can count on me rating your post!

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