none
Read/Write to file method?

    Question

  • Hi Guys I'm a newbie programmer with the only back ground of finishing the intro to java programming course. I think i'm starting to get the hang of it all though so I'm trying to find what language to jump into one by one so in vb I have reached a sort of hiccup. I am make a character sheet of sorts and I am trying to save all the fields into one text file. I have found a few tutorials which show many different ways to write to a txt, but they seem pretty complex. Is there something more like this  

    point to  C:/myducuments/    

        write.Totxt(textbox1.text,"test.txt", ln 1)

    point to  C:/myducuments/

        textbox1.text = Read.Fromtxt("test.txt", ln 1)

    If nothing this simple exists could someone be able to write one that I could just copy?


    Saturday, March 11, 2017 9:18 PM

Answers

  • Lets have a bit of fun using VS2015 (with string interpolation), two classes to strong type if something is returned the line number, zero based and the entire line. Lastly exception handling.

    Public Class Operations
        Private _path As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
        Public HasErrors As Boolean
        Public Exception As Exception
        Public ReadOnly Property Path As String
            Get
                Return _path
            End Get
        End Property
        Public Function WriteText(ByVal FileName As String, ByVal Line As String) As Boolean
            HasErrors = False
            Try
                IO.File.WriteAllText(IO.Path.Combine(Me.Path, FileName), Line)
                Return True
            Catch ex As Exception
                HasErrors = True
                Me.Exception = ex
                Return False
            End Try
        End Function
        ''' <summary>
        ''' Read file, look for the first instance of SearchFor
        ''' </summary>
        ''' <param name="FileName">File to read from</param>
        ''' <param name="SearchFor">item to search for</param>
        ''' <param name="Result">If success a SearchItem item</param>
        ''' <returns></returns>
        ''' <remarks>
        ''' NOTE that this is a basic example which can be expanded
        ''' on to search for
        ''' * full match
        ''' * partial match - starts with, contains, ends with and case insensitive
        ''' * multiple matches
        ''' </remarks>
        Public Function ReadFindItem(ByVal FileName As String, ByVal SearchFor As String, ByRef Result As SearchItem) As Boolean
            HasErrors = False
            Try
                If IO.File.Exists(IO.Path.Combine(Me.Path, FileName)) Then
    
                    Dim SearchResult As SearchItem = IO.File.ReadLines(IO.Path.Combine(Me.Path, FileName)) _
                        .Select(Function(line, index) New SearchItem With {.Text = line.ToLower, .LineNumber = index}) _
                        .Where(Function(data) data.Text.Contains(SearchFor.ToLower)).FirstOrDefault
    
                    If SearchResult IsNot Nothing Then
                        Result = SearchResult
                        Return True
                    Else
                        Return False
                    End If
                Else
                    Return False
                End If
            Catch ex As Exception
                HasErrors = True
                Me.Exception = ex
                Return False
            End Try
        End Function
    End Class
    
    Public Class SearchItem
        Public Property LineNumber As Integer
        Public Property Text As String
        Public Overrides Function ToString() As String
            Return $"{LineNumber},{Text}"
        End Function
    End Class

    Form code

    Dim name As String = "Jonn"
    Dim x As String = "10"
    Dim AnotherName As String = "Mary"
    Dim y As String = "4"
    
    Dim sb As New Text.StringBuilder
    
    sb.AppendLine(name)
    sb.AppendLine(x)
    sb.AppendLine(AnotherName)
    sb.AppendLine(y)
    
    Dim ops = New Operations
    Dim contents As New SearchItem
    Dim FileName As String = "Demo.txt"
    
    
    If ops.WriteText(FileName, sb.ToString) Then
        MessageBox.Show("Written")
        If ops.ReadFindItem(FileName, AnotherName, contents) Then
            MessageBox.Show($"{contents.ToString}")
        Else
            MessageBox.Show($"{IO.Path.Combine(ops.Path, FileName)} not found")
        End If
    Else
        MessageBox.Show("Failed to write")
    End If

    What it does not have is multiple writes to the file which I didn't see asked yet it would be easy to do.

    We could add this to the class above

    Public Sub Read(ByVal FileName As String)
        Dim SearchResult As List(Of SearchItem) = IO.File.ReadLines(IO.Path.Combine(Me.Path, FileName)) _
            .Select(Function(line, index) New SearchItem With {.Text = line.ToLower, .LineNumber = index}).ToList
    End Sub


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Saturday, March 11, 2017 10:50 PM
    Moderator

All replies

  • Hello,

    Here is an example

    My.Computer.FileSystem _ 
        .WriteAllText(
        IO.Path.Combine(
        My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt"), TextBox1.Text, True)

    Read it back

    Dim contents = IO.File.ReadAllText(
        IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt"))


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Saturday, March 11, 2017 9:43 PM
    Moderator
  • Aaron, 

    Despite that is seems to be the program language, in .Net your question is all about .Net. 

    In all .Net program languages the solutions are in fact the same. I've despite that my first language is not English a preference for VB. 

    It is so natural to write. However, I'm an alpha. If you are a Beta guy you probably would go for a C type (C# but also Java and C++) kind of language. If you want a more stringetly program language you can choice F#. 

    However, in all those program languages in .Net it would mean. 

    Variable = System.Io.Files.ReadAllText(path)

    And then you have hundreds of alternatives. 


    Success
    Cor

    Saturday, March 11, 2017 10:07 PM
  • thank you for the quick feed back but I am not sure this helps or maybe it dose and I just don't under stand.

    what you rote there looks like what everyone has been sending and to me it just looks like it takes the content of one textbox and puts it into a text file. what I am trying to do is take multiple textboxes and other feilds and store there values into the text file and read them back as a sort of line selection. 

    dim name as string = "Jonn"

    dim x as string = "10"

    dim y as string = "4"

    write.Totxt(name,"test.txt", ln 1)

    write.Totxt(x,"test.txt", ln 2)

    write.Totxt(y,"test.txt", ln 3)

    --------------------------

    For example: textfile.txt

    John

    10

    4

    ____________________

     textbox1.text = Read.Fromtxt("test.txt", ln 2)

    -----------------------------

    'textbox1.text now reads 10


    Saturday, March 11, 2017 10:27 PM
  • So Confused. I don't think you understand the question
    Saturday, March 11, 2017 10:31 PM
  • Strange, seems to be a bug again in this forum, I made a reply and it is gone. 


    Success
    Cor

    Saturday, March 11, 2017 10:39 PM
  • ... take multiple textboxes and other feilds and store there values into the text file and read them back as a sort of line selection. 

    dim name as string = "Jonn"

    dim x as string = "10"

    dim y as string = "4"


    That looks like you're trying to use encapsulation - as from a class - and then from that, persist the data to file.

    Does that sound like what you're looking for?


    "One who has no vices also has no virtues..."

    Saturday, March 11, 2017 10:40 PM
  • Lets have a bit of fun using VS2015 (with string interpolation), two classes to strong type if something is returned the line number, zero based and the entire line. Lastly exception handling.

    Public Class Operations
        Private _path As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
        Public HasErrors As Boolean
        Public Exception As Exception
        Public ReadOnly Property Path As String
            Get
                Return _path
            End Get
        End Property
        Public Function WriteText(ByVal FileName As String, ByVal Line As String) As Boolean
            HasErrors = False
            Try
                IO.File.WriteAllText(IO.Path.Combine(Me.Path, FileName), Line)
                Return True
            Catch ex As Exception
                HasErrors = True
                Me.Exception = ex
                Return False
            End Try
        End Function
        ''' <summary>
        ''' Read file, look for the first instance of SearchFor
        ''' </summary>
        ''' <param name="FileName">File to read from</param>
        ''' <param name="SearchFor">item to search for</param>
        ''' <param name="Result">If success a SearchItem item</param>
        ''' <returns></returns>
        ''' <remarks>
        ''' NOTE that this is a basic example which can be expanded
        ''' on to search for
        ''' * full match
        ''' * partial match - starts with, contains, ends with and case insensitive
        ''' * multiple matches
        ''' </remarks>
        Public Function ReadFindItem(ByVal FileName As String, ByVal SearchFor As String, ByRef Result As SearchItem) As Boolean
            HasErrors = False
            Try
                If IO.File.Exists(IO.Path.Combine(Me.Path, FileName)) Then
    
                    Dim SearchResult As SearchItem = IO.File.ReadLines(IO.Path.Combine(Me.Path, FileName)) _
                        .Select(Function(line, index) New SearchItem With {.Text = line.ToLower, .LineNumber = index}) _
                        .Where(Function(data) data.Text.Contains(SearchFor.ToLower)).FirstOrDefault
    
                    If SearchResult IsNot Nothing Then
                        Result = SearchResult
                        Return True
                    Else
                        Return False
                    End If
                Else
                    Return False
                End If
            Catch ex As Exception
                HasErrors = True
                Me.Exception = ex
                Return False
            End Try
        End Function
    End Class
    
    Public Class SearchItem
        Public Property LineNumber As Integer
        Public Property Text As String
        Public Overrides Function ToString() As String
            Return $"{LineNumber},{Text}"
        End Function
    End Class

    Form code

    Dim name As String = "Jonn"
    Dim x As String = "10"
    Dim AnotherName As String = "Mary"
    Dim y As String = "4"
    
    Dim sb As New Text.StringBuilder
    
    sb.AppendLine(name)
    sb.AppendLine(x)
    sb.AppendLine(AnotherName)
    sb.AppendLine(y)
    
    Dim ops = New Operations
    Dim contents As New SearchItem
    Dim FileName As String = "Demo.txt"
    
    
    If ops.WriteText(FileName, sb.ToString) Then
        MessageBox.Show("Written")
        If ops.ReadFindItem(FileName, AnotherName, contents) Then
            MessageBox.Show($"{contents.ToString}")
        Else
            MessageBox.Show($"{IO.Path.Combine(ops.Path, FileName)} not found")
        End If
    Else
        MessageBox.Show("Failed to write")
    End If

    What it does not have is multiple writes to the file which I didn't see asked yet it would be easy to do.

    We could add this to the class above

    Public Sub Read(ByVal FileName As String)
        Dim SearchResult As List(Of SearchItem) = IO.File.ReadLines(IO.Path.Combine(Me.Path, FileName)) _
            .Select(Function(line, index) New SearchItem With {.Text = line.ToLower, .LineNumber = index}).ToList
    End Sub


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Saturday, March 11, 2017 10:50 PM
    Moderator
  • Strange, seems to be a bug again in this forum, I made a reply and it is gone. 


    Success
    Cor

    The only thing I see is a deleted reply by the OP.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Saturday, March 11, 2017 10:57 PM
    Moderator

  • That looks like you're trying to use encapsulation - as from a class - and then from that, persist the data to file.

    Does that sound like what you're looking for?


    "One who has no vices also has no virtues..."

    No not really. I just want to store multiple line of string to a txt file and be able to pull what ever string I need back out and assign it where ever I may need it. I could see this being used for purposes such as taking usernames and passwords, storing a games saved data....
    Saturday, March 11, 2017 10:58 PM
  • I just want to store multiple line of string to a txt file and be able to pull what ever string I need back out and assign it where ever I may need it. I could see this being used for purposes such as taking usernames and passwords, storing a games saved data....

    If you just mean the equivalent of one instance of a class, then it's as simple as string manipulation and the text file itself.

    The simplest form of encapsulation: A delimited text file. :)

    Do you want me to put an example together and post?


    "One who has no vices also has no virtues..."

    Saturday, March 11, 2017 11:02 PM
  • Lets have a bit of fun using VS2015 (with string interpolation), two classes to strong type if something is returned the line number, zero based and the entire line. Lastly exception handling.

    Public Class Operations
        Private _path As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
        Public HasErrors As Boolean
        Public Exception As Exception
        Public ReadOnly Property Path As String
            Get
                Return _path
            End Get
        End Property
        Public Function WriteText(ByVal FileName As String, ByVal Line As String) As Boolean
            HasErrors = False
            Try
                IO.File.WriteAllText(IO.Path.Combine(Me.Path, FileName), Line)
                Return True
            Catch ex As Exception
                HasErrors = True
                Me.Exception = ex
                Return False
            End Try
        End Function
        ''' <summary>
        ''' Read file, look for the first instance of SearchFor
        ''' </summary>
        ''' <param name="FileName">File to read from</param>
        ''' <param name="SearchFor">item to search for</param>
        ''' <param name="Result">If success a SearchItem item</param>
        ''' <returns></returns>
        ''' <remarks>
        ''' NOTE that this is a basic example which can be expanded
        ''' on to search for
        ''' * full match
        ''' * partial match - starts with, contains, ends with and case insensitive
        ''' * multiple matches
        ''' </remarks>
        Public Function ReadFindItem(ByVal FileName As String, ByVal SearchFor As String, ByRef Result As SearchItem) As Boolean
            HasErrors = False
            Try
                If IO.File.Exists(IO.Path.Combine(Me.Path, FileName)) Then
    
                    Dim SearchResult As SearchItem = IO.File.ReadLines(IO.Path.Combine(Me.Path, FileName)) _
                        .Select(Function(line, index) New SearchItem With {.Text = line.ToLower, .LineNumber = index}) _
                        .Where(Function(data) data.Text.Contains(SearchFor.ToLower)).FirstOrDefault
    
                    If SearchResult IsNot Nothing Then
                        Result = SearchResult
                        Return True
                    Else
                        Return False
                    End If
                Else
                    Return False
                End If
            Catch ex As Exception
                HasErrors = True
                Me.Exception = ex
                Return False
            End Try
        End Function
    End Class
    
    Public Class SearchItem
        Public Property LineNumber As Integer
        Public Property Text As String
        Public Overrides Function ToString() As String
            Return $"{LineNumber},{Text}"
        End Function
    End Class

    Form code

    Dim name As String = "Jonn"
    Dim x As String = "10"
    Dim AnotherName As String = "Mary"
    Dim y As String = "4"
    
    Dim sb As New Text.StringBuilder
    
    sb.AppendLine(name)
    sb.AppendLine(x)
    sb.AppendLine(AnotherName)
    sb.AppendLine(y)
    
    Dim ops = New Operations
    Dim contents As New SearchItem
    Dim FileName As String = "Demo.txt"
    
    
    If ops.WriteText(FileName, sb.ToString) Then
        MessageBox.Show("Written")
        If ops.ReadFindItem(FileName, AnotherName, contents) Then
            MessageBox.Show($"{contents.ToString}")
        Else
            MessageBox.Show($"{IO.Path.Combine(ops.Path, FileName)} not found")
        End If
    Else
        MessageBox.Show("Failed to write")
    End If

    What it does not have is multiple writes to the file which I didn't see asked yet it would be easy to do.

    We could add this to the class above

    Public Sub Read(ByVal FileName As String)
        Dim SearchResult As List(Of SearchItem) = IO.File.ReadLines(IO.Path.Combine(Me.Path, FileName)) _
            .Select(Function(line, index) New SearchItem With {.Text = line.ToLower, .LineNumber = index}).ToList
    End Sub


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    thank for the help but I am a bit confused on how you call back the values stored could you give an example of how to retrieve the values john and 4  and assign them to a string of like X or something?
    Sunday, March 12, 2017 12:03 AM
  • Here is my prior reply I'm looking for Mary in the variable AnotherName.

    Here I'm looking Jonn w/o a variable

    Dim ops = New Operations
    Dim contents As New SearchItem
    Dim FileName As String = "Demo.txt"
    
    If ops.ReadFindItem(FileName, "Jonn", contents) Then
        MessageBox.Show($"{contents.ToString}")
    Else
        MessageBox.Show($"{IO.Path.Combine(ops.Path, FileName)} not found")
    End If


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Sunday, March 12, 2017 1:04 AM
    Moderator