Results 1 to 19 of 19

Thread: Textfiles in vb.net

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    16

    Textfiles in vb.net

    Hi! I would like to create a system for my housedetail tracker. I would like to store the following details:

    ID
    FirstName
    Surname

    I can only use textfiles ! What is the best way to write, view (retrieve), delete and update records to make it simple as I have 3 details I am storing.

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: Textfiles in vb.net

    What do you mean by text files? If you are allowed to use any file that can be read as text, then use XML files, as that will make everything else much easier. If you actually meant CSV, then you can make that somewhat easier, as well. If you meant files with an extension of .txt, then use XML and change the file extension.

    So, the first question is just what you mean by text files. What you do with the file will depend on what the actual limitations are. For example, the thing that makes XML files so utterly simple for this is that the Datatable has .ReadXML and WriteXML methods, so reading/writing to the file is nothing more than a single line, and you end up with all the data in a datatable, which makes it VERY easy to display, search, and so forth.
    My usual boring signature: Nothing

  3. #3
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Textfiles in vb.net

    There is far too much information missing to tell you what is the "best".

    As SH points out, "text file" means a lot of different things. "I can only use text files" is a curious requirement, is this homework? If so, does the homework provide any information about what those text files should contain?

    Do you insert at the back? Do you need random access? Do you need to filter or search? How many items will be saved? A ton of these questions affect what "best" implementation you should pick.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    16

    Re: Textfiles in vb.net

    I created it ! however I want to be able to edit these three records if selected and reinsert in the ".dat" file data file. They are currently also outputting to a textbox . I am using random access. To add to a file im using the following :

    Code:
            Dim OneZookeeper As Zookeeper
            Dim ID As String
            Dim MembersDeleted As Boolean
            Dim Duplicate As Boolean
            Dim Responce As Short  
            Dim Zoofile as string
    
    
            Zoofile= "Zoo.dat"
            If Btn_AddNewZookeepr.Text = "Add Zookeper" Then
                If Tbx_ID.Text.Length = 10 Then
                    ID = Tbx_ID.Text
     OneZookeeper.AdminID = Tbx_ID.Text
                         OneZookeeper.Fname = tbx_Fname.text
                          OneZookeeper.Sname = tbx_Sname.text
                       
    Call AddZookeeper(OneZookeeper)
    AddZookeeper proedure ()

    Code:
     Private Sub AddZookeeper(ByRef OneZooKeeper As Zookeeper)
    
            Dim NumbersOfRecords, DeletedRecordNumber As Short
            Dim Sender As System.Object
            Dim e As System.EventArgs
          FileOpen(1, Zoofile, OpenMode.Random, , , Len(OneZookeeper))
    
            If DeletedRecordNumber <> 0 Then
                FilePut(1, OneAdmin, DeletedRecordNumber)
            Else
                NumbersOfRecords = LOF(1) / Len(OneZookeeper)
                FilePut(1, OneZookeeper, NumbersOfRecords + 1)
    
            End If
            FileClose(1)
    
    
        End Sub

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: Textfiles in vb.net

    That's legacy file handling (and some other legacy stuff). Still works, though, so if it's all you need, then stick with it....or not. That's up to you. You're kind of stuck with a system like that if you are forced to use barely structured files. If you aren't forced to use files like that, then switch to something that will make your life easier.

    By the way, why are you declaring sender and e? You don't appear to be using those, but based on the names, I would assume that you declared them because you were calling an event handler directly. If that's the case, the best suggestion is to not do that (there are other ways), but even if you do want to call an event handler directly, there's no reason to bother creating those arguments. Neither one would be at all useful in the method, so you might as well just pass in Nothing for both and be done with it.
    My usual boring signature: Nothing

  6. #6
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: Textfiles in vb.net

    What is the definition of Zookeeper?
    Also, using the old VisualBasic Random access filemode is technically not a text file, as you could be writing non-text based data to the file.

    I used to use Random a lot with VB6, but haven't used it at all with VB.Net, so I don't know if there are some subtle differences in the way using the ported old methods (i.e. FileOpen, FilePut, FileGet for the VB6 Open, Put, Get methods) work compared to VB6.

    A question, assuming you continue with the older style methods, is how you want the record system to work. It looks like you plan on "tagging" deleted records by writing some preset type "OneAdmin" into an existing record.
    Do you plan on always leaving those records there, i.e. you won't ever reuse those slots in your file? Any new records will always be appended.
    I never cared for dividing the size of the file by the size of a record to find out how many records were in a file, probably because I often used the random file to hold different types of data in a given file slot, so the size of the record written wouldn't necessarily be the same.
    I would usually use the first slot of the file to hold some metadata, like how many records were in the file. If I didn't care about the order of the data in the file, I could simply delete a record by copying the last record in the file over the one to be deleted, and reduce my record count by one.
    In other cases, I might use the first record to hold the number of slots in the file, the number of active records in the file, and two "pointers" to point to two records in the file, one record being the first record of a linked list for active records, and the other as the first record for a linked list of deleted records. I could "remove" a record from the deleted records list to use in the active records list, and vice versa to delete a record. I would only have to increase the file size if I ran out of deleted records.

    You should probably be able to write up a description of how you expect to add records, delete records, access the records, etc... so that what the code might look like to fulfill those "requirments" could be accomplished.
    But, I'm pretty sure there are simpler methods compared to using the old random record file format, but if you really feel that the old random access method is what you want, then describe how you want it to work, i.e. how would you generate a list of the current records, how would you determine the number of active records, vs. deleted records. Do you plan on having a method of "flattening" the file, i.e. removing the deleted records by packing active records toward the front of the file, etc...
    Last edited by passel; Dec 20th, 2017 at 05:51 PM.

  7. #7

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    16

    Re: Textfiles in vb.net

    Thanks for both of your lovely support !

    Im not sure what would be the easiest way of deleting records in the way I have done it ?

  8. #8
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Textfiles in vb.net

    We're not really sure either, because only a small portion of VB .NET experts have experience with methods like FilePut(). They were obsoleted in 2003. There are plenty of arguments as to whether what came after was better or not, but right now the biggest problem you face is, "Many VB experts aren't experienced with them because they haven't needed them for 14 years."
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: Textfiles in vb.net

    I don't think I have EVER dealt with random access files, as I was always working with databases from early on. However, the folks who WOULD have experience with this would tend to be the folks who frequent Classic VB, since this was largely a VB6 thing. I'm not going to move the thread, though, because you don't generally want to mention that you are working in .NET. Most don't care, but they'd likely just assume you had posted in the wrong forum and ignore the question. So, you might start a thread over there about deleting from a random access file, just don't post code if you can avoid it.
    My usual boring signature: Nothing

  10. #10
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,532

    Re: Textfiles in vb.net

    Quote Originally Posted by Itsmethecoder123 View Post
    Thanks for both of your lovely support !

    Im not sure what would be the easiest way of deleting records in the way I have done it ?
    The same way it's been done for years in VB6.
    I'm making an assumption: The file was read into records into a list(of) or at the very least an array.
    So then, it's just a matter of removing it from the list or array, opening the file (for writing, not appending) and then writing the records back to the file.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  11. #11
    Smooth Moperator techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,532

    Re: Textfiles in vb.net

    Quote Originally Posted by Shaggy Hiker View Post
    I don't think I have EVER dealt with random access files, as I was always working with databases from early on. However, the folks who WOULD have experience with this would tend to be the folks who frequent Classic VB, since this was largely a VB6 thing. I'm not going to move the thread, though, because you don't generally want to mention that you are working in .NET. Most don't care, but they'd likely just assume you had posted in the wrong forum and ignore the question. So, you might start a thread over there about deleting from a random access file, just don't post code if you can avoid it.
    It's been a long while since I've used RAFs ... I pretty much stopped using them when I discovered serialization and how easy that is in .NET. After that, it was RAF - Game Over. Didn't seem to be much point in staying down that road. I suspect the same it true for anyone else that made the VB6->VB.NET leap and previously used RAF.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  12. #12
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    6,582

    Re: Textfiles in vb.net

    Quote Originally Posted by Itsmethecoder123 View Post
    Thanks for both of your lovely support !

    Im not sure what would be the easiest way of deleting records in the way I have done it ?
    I didn't quite recognize that as an actual question.
    Given the way "you've done it", what is your current question?

    You mentioned you wanted to be able to edit those fields and write them back to the file, so how do you want that interface to work?
    For instance, do you want to provide a list of all the records in the file and the user choose one to edit.
    Sometimes you may want to choose one to edit and write back to the same record, but in other cases you might want to choose one, make edits, and then add it back as a new record, using the one you selected as a template or starting point for a new record.

    At the simplest, you could have a button for navigating down, one for navigating up, one for update (i.e. editing an existing record) and one for adding a new record.
    You could then use the one set of existing textboxes for displaying, editing and adding records to the file.
    For instance, you start up the program, and if records exist in the file, perhaps it would find the last record added and display the "fields" in the textboxes. You could then use a "Previous" button to work your way down through the records, displaying the values in the textbox as you go. When you find one you want to change, you make the changes in the textbox, and then hit the update button to write that record back to the current index you were displaying.
    If you wanted to add a new record, you would just modify the textboxes and hit the Add button and write it to a new record at the end of the file.
    To delete the record, you can do what you're doing. You would step through until you find one you want to delete and then you would just write your "empty" record (whatever OneAdmin is) to that index.
    When you step up and down displaying the contents, you can choose whether you skip over "deleted" records, or perhaps you would want to display them so they could be edited back into a valid record again.

    You still didn't show what the definitions for OneAdmin and ZooKeeper are, so I can't tell if what you have already is really viable and won't bother trying to test with a Class or Structure of my own design that may not be applicable. I don't quite have that much initiative right now.

  13. #13
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,116

    Re: Textfiles in vb.net

    I've worked with random files recently in VB.NET.

    OP, for deleting records, there are a several options, here are a few.

    One option is to simple write an "empty" record on top of the existing record.

    Code:
    Private Sub DeleteRecord(ByVal RecordNumber As Integer)
    
      Dim EmptyRecord As Zookeeper
      FilePut(1, EmptyRecord, RecordNumber)
    
    End Sub
    That will leave you with a blank record that can be reused, but your code would need to accommodate searching for an empty record in the middle of the file to reuse.


    Another option is to leave the record mostly intact but flag it as deleted by modifying one of the fields to mark it as deleted. For example, you could define a deleted record as having an ID value of -99.

    Code:
    Private Sub DeleteRecord(ByVal RecordNumber As Integer)
    
      Dim FlaggedRecord As Zookeeper
      FileGet(1, FlaggedRecord, RecordNumber)
      FlaggedRecord.ID = -99   ' If ID is defined as a string you need to put quotes around -99
      FilePut(1, FlaggedRecord, RecordNumber)
    
    End Sub
    Then you would include code in your program to properly handle (which would most likely be to ignore) records with an ID of -99


    A third option would be to delete the record by moving all records "below" it up one slot.

    Code:
    Private Sub DeleteRecord(ByVal RecordNumber As Integer)
    
      Dim intIndex As Integer
      Dim tmpZookeeper As Zookeeper
    
      For intIndex = RecordNumber To NumberOfRecords -  1
        FileGet(1, tmpZookeeper, intIndex + 1)
        FilePut(1, tmpZookeeper, intIndex)
      Next
    
      Dim EmptyRecord As Zookeeper
      FilePut(1, EmptyRecord, NumberOfRecords)
    
    End Sub
    The caveat with this option is that the file will include an empty record at the end which can potentially skew the "NumberOfRecords" calculation. So, say you had 10 records, you delete record 6. Old record 7 moves to slot 6, 8 moves to 7, etc. There will be 9 records with data in your file, but your file will still have a size of 10 records, with the 10th record being blank (slack space). So again, you may need to add extra code to handle that if you wish.

    If you want to ensure that the file only ever contains active records with no slack space, then you could do something like read all records into an array, shuffle things around in the array, delete the random access file, and then recreate the random access file with only the active records.

    Does that help answer your question about deleting records?

  14. #14
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,046

    Re: Textfiles in vb.net

    Hi Itsme,

    whay not use a Database ?

    here a sample that will create the Database and the Table,
    I added a Datagridview for retrieving the Data from the Table

    you have to set references to MS ADO Ext. 2.x for DDL and Security

    add two Buttons and a Datagridview to the Form
    Code:
    'set references to MS ADO Ext. 2.x for DDL and Security 
    
    Imports System.Data.OleDb
    Public Class Form1
    
        Public Function CreateDatabase(ByVal MDBName As String, _
                                          Optional ByVal Password As String = Nothing, _
                                          Optional ByVal EngineType As Int32 = 5, _
                                          Optional ByVal ErrMessage As String = Nothing) As Boolean
    
            Dim Sw As New System.IO.StringWriter
    
            Sw.Write("Provider=Microsoft.Jet.OLEDB.4.0;")
            Sw.Write("Jet OLEDB:Engine Type = {0};", EngineType.ToString)
            Sw.WriteLine("Data Source={0}", MDBName)
            If Not Password = Nothing Then
                Sw.Write(";Jet OLEDB:Database Password={0}", Password)
            End If
    
            Try
                Dim Cat As New ADOX.Catalog
                Cat.Create(Sw.ToString)
                Dim Msg As String = "Fehler bei Freigabe ADOX.Cat"
                If Not ReleaseComObject(Cat.ActiveConnection) Then
                    ErrMessage = Msg
                    Return False
                ElseIf Not ReleaseComObject(Cat) Then
                    ErrMessage = Msg
                    Return False
                End If
                Return True
    
            Catch ex As Exception
                ErrMessage = ex.Message
                Return False
            End Try
    
            Return True
        End Function
        Public Sub CreateTable()
            Dim sSQL As String
            Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\ZooKeeper.mdb")
            'here you create your Table in the Database
            sSQL = sSQL & "  Create Table tbl_Zoo"
            sSQL = sSQL & "( [ZO_ID] Integer Identity"
            sSQL = sSQL & ", [ZO_Firstname] varChar(50)"
            sSQL = sSQL & ", [ZO_Surname] varChar(50) "
            sSQL = sSQL & ")"
            con.Open()
            ExecuteSQL(con, sSQL)
            con.Close()
            con = Nothing
        End Sub
    
        Public Sub CreateIndex()
            Dim sSQL As String
            Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\ZooKeeper.mdb")
            sSQL = sSQL & "Alter Table [tbl_Zoo] Add Constraint [PrimaryKey] Primary Key (ZO_ID)"""
            con.Open()
            ExecuteSQL(con, sSQL)
            con.Close()
            con = Nothing
        End Sub
        Public Sub CreateSampleData()
            Dim sSQL As String
            Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\ZooKeeper.mdb")
            'add some Data to the Table in the Database
            sSQL = sSQL & "  Insert Into tbl_Zoo (ZO_Firstname,ZO_Surname)Values ('Daktari','Cheeta')"
            con.Open()
            ExecuteSQL(con, sSQL)
            con.Close()
            con = Nothing
        End Sub
    
        Private Function ReleaseComObject(ByVal objCom As Object) As Boolean
            Dim Result As Integer = 0
            For i As Integer = 0 To 9
                Result = Runtime.InteropServices.Marshal.FinalReleaseComObject(objCom)
                If Result = 0 Then
                    Return True
                End If
                System.Threading.Thread.Sleep(0)
                Application.DoEvents()
            Next
            Return False
        End Function
    
        Public Function ExecuteSQL(ByVal Con As OleDb.OleDbConnection, _
                                         ByVal sSQL As String, _
                                         Optional ByRef ErrMessage As String = Nothing, _
                                         Optional ByVal TransAction As  _
                                         OleDb.OleDbTransaction = Nothing) As Integer
            ErrMessage = Nothing
            Try
                Dim Result As Integer = 0
                Using Cmd As New OleDb.OleDbCommand(sSQL, Con, TransAction)
                    Result = Cmd.ExecuteNonQuery
                End Using
                Return Result
            Catch ex As Exception
                ErrMessage = ex.Message
                Return 0
            End Try
        End Function
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            'Create the Database and the Table
            CreateDatabase("C:\ZooKeeper.mdb", , 5, )
            CreateTable()
            CreateIndex()
            CreateSampleData()
        End Sub
    
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            Dim strSql As String
            strSql = "SELECT * From tbl_Zoo; "
    
            Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\ZooKeeper.mdb")
    
            Dim cmd As OleDbCommand = New OleDbCommand(strSql, con)
            con.Open()
            Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
            Dim myDataSet As DataSet = New DataSet()
            myDA.Fill(myDataSet, "MyT")
            DataGridView1.DataSource = myDataSet.Tables("MyT").DefaultView
            con.Close()
            con = Nothing
    
        End Sub
    End Class
    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  15. #15

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    16

    Re: Textfiles in vb.net

    This is brilliant ! thanks a lot OptionBase1 you are the type of people that give the best feedback !!!

    As for the rest I really appreciate the input ! I am stuck with using textfiles unfortunately. I just am having trouble currently with using a datagridview because when i write to my file basically just stores it all in one line so i need to resolve that

  16. #16
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,046

    Re: Textfiles in vb.net

    Hi,

    why are you stuck with using only Textfiles ?

    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  17. #17
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,116

    Re: Textfiles in vb.net

    Quote Originally Posted by Itsmethecoder123 View Post
    This is brilliant ! thanks a lot OptionBase1 you are the type of people that give the best feedback !!!

    As for the rest I really appreciate the input ! I am stuck with using textfiles unfortunately. I just am having trouble currently with using a datagridview because when i write to my file basically just stores it all in one line so i need to resolve that
    I think you are misunderstanding how random files work.

    If I have a structure with two elements, like:

    Code:
    Private Structure myStruc
      <VBFixedString(2)> Public StateAbbreviation As String
      <VBFixedString(5)> Public ZipCode As String
    End Structure
    And I do this:

    Code:
    Dim sMyStruc1 As myStruc
    Dim sMyStruc2 As myStruc
    
    sMyStruc1.StateAbbreviation = "CA"
    sMyStruc1.ZipCode = "90210"
    sMyStruc2.StateAbbreviation = "NY"
    sMyStruc2.ZipCode = "10013"
    
    FilePut (1, sMyStruc1, 1)
    FilePut (1, sMyStruc2, 2)
    It sounds like you are assuming the resulting file will look like this:

    Code:
    CA90210
    NY10013
    It won't, it will look like this:

    Code:
    CA90210NY10013
    Random files don't separate records with newline characters. They aren't separated by anything, one record begins the byte after the previous records ends.

    That being said, if you are trying to use code like in this thread http://www.vbforums.com/showthread.p...rom-a-txt-file to populate the DataGridView, then you shouldn't be using a random access file to store the data.

  18. #18

    Thread Starter
    Junior Member
    Join Date
    Dec 2017
    Posts
    16

    Re: Textfiles in vb.net

    thats exactly what i mean !

    that link shows the delimited version.

    How would i write to delimited text files and retreive data to textboxes then? (using delimited textfiles)

    Appreciate the help and support

    Happy holidays!

  19. #19
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,116

    Re: Textfiles in vb.net

    Check out the information on this page:

    http://www.codescratcher.com/windows...ile-in-vb-net/

    This will walk you through the process of creating csv (comma separated) files.

    Then, with the code from the thread I linked to above, you should be able to read the data back into a DataGridView, but since the data is comma separated rather than tab separated, you'd need to change one partial line of code:

    Code:
    Select line.Split(CChar(vbTab))).ToArray
    to the following (I think):

    Code:
    Select line.Split(",")).ToArray

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