Question Working with Structure

cgcg

New member
Joined
Mar 31, 2013
Messages
1
Programming Experience
Beginner
Hi,

I want to write data to a txt file using vb 2012 structure. I have a form with 3 textbox, one for Name, one for LastName and one for Age. when a run the program i'm having error on the FILEPUT line. And when a open the file (prueba.txt) is empty. Please help , any good advise on it.

here is my code:
Imports System.IO
Public Class Form1

'Create a record type. The name of the record
'structure is given as “Person”.
Public Structure Person
Public Name As String
Public LastName As String
Public Age As String
End Structure


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim client As New Person
Dim RecordNumber As Integer

With client
.Name = TextBox1.Text
.LastName = TextBox2.Text
.Age = TextBox3.Text

End With
FileOpen(1, My.Computer.FileSystem.SpecialDirectories.MyDocuments & "prueba.txt", OpenMode.Random, OpenAccess.Write, OpenShare.LockWrite, Len(client))

RecordNumber = 1
FilePut(1, client, RecordNumber)
FileClose(1)

End Sub
 
Hi,

You do not give any indication of what the error is that you are getting but, from what I can see, there are two issues with this statement:-

VB.NET:
FileOpen(1, My.Computer.FileSystem.SpecialDirectories.MyDocuments & "prueba.txt", OpenMode.Random, OpenAccess.Write, OpenShare.LockWrite, Len(client))

The first issue is the filename. As you have it now you will be saving to a file name along the lines of:-

VB.NET:
C:\Users\YourUserName\Documentsprueba.txt

When I am guessing it should be:-

VB.NET:
C:\Users\YourUserName\Documents\prueba.txt

So, you need to change your filename to "\prueba.txt"

Secondly, I have never used FileOpen in .NET, but after a quick test, the RecordLength element of this statement causes an Invalid File Length error, so just get rid this and the file will save fine.

If you now find that you have trouble reading your file back into your Person Structure you may want to look into Serialization, using either a Binary or XML Formatter to read and write your files.

Hope that helps.

Cheers,

Ian
 
Back
Top