Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

saving to disk

Status
Not open for further replies.

orisons

Programmer
Feb 18, 2002
49
0
0
CA
this may seem strange but!!!!!
I am still reading books on this stuff and I have found that my questions have been better answered on this forum, I cant get to grips with saving data to disk (hard disk) all I want to do is save any settings on forms that have been changed you know like text1.caption = "ha ha I changed it", so that when the prog starts these load as the settings any help would be much appriciatted
thankyou
 
One method is to read and write to an ini file.

---------------------------------------------------------
Paste this code into your Form Code Module

Public Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Public Declare Function GetPrivateProfileInt Lib "kernel32" Alias "GetPrivateProfileIntA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal nDefault As Long, ByVal lpFileName As String) As Long

Public Const MyINI as string = App.Path & "\SomeAppropriateName.ini"


Public Sub Form_Load()
On Error GoTo ErrorHandler
Dim Temp As String * 300
Dim ReadLine As Integer
ReadLine = GetPrivateProfileString("SETTINGS", "Txt1Cap", "DefaultValue", Temp, Len(Temp), MyINI)
Text1.Text = Left$(Temp, Len(Temp))
ReadLine = GetPrivateProfileString("SETTINGS", "Txt2Cap", "DefaultValue", Temp, Len(Temp), MyINI)
Text2.Text = Left$(Temp, Len(Temp))
ReadLine = GetPrivateProfileString("SETTINGS", "Txt2Cap", "DefaultValue", Temp, Len(Temp), MyINI)
ReadLine = GetPrivateProfileString("SETTINGS", "FrmBGColour", "&H8000000B", Temp, Len(Temp), MyINI)
Me.BackColor = Left$(Temp, Len(Temp))
Exit Sub
ErrorHandler:
MsgBox Err.Number & " " & Err.Description
End Sub



Public Sub Form_UnLoad()
Dim WriteLine As Integer
WriteLine = WritePrivateProfileString("SETTINGS", "Txt1Cap", Text1.Text, MyINI)
WriteLine = WritePrivateProfileString("SETTINGS", "Txt2Cap", Text1.Text, MyINI)
End Sub



--------------------------------------------------------
Open Notepad and create a file called SomeAppropriateName.ini and save your applications path.

Inside this file Paste the following

[SETTINGS]
Txt1Cap=TESTING CAPTION 1
Txt2Cap=TESTING CAPTION 2
FrmBGColour=&H80000003

--------------------------------------------------------
 
I realy think that there is a more quickly modality to do what you want.

To open a file for Output use something like this:
Code:
Open "c:\file.dat" For Output As #1 Len = 32767
        Print #1, Text1.Text
        Print #1, Form1.BackColor
Close 1
To open a file for Appending use something like this:
Code:
Open "c:\file.dat" For Append As #1 Len = 32767
        Print #1, Text1.Text
        Print #1, Form1.BackColor
Close 1
To open a file for input and to read lines, you showld declare Line1 and Line2 and use something like:
Code:
Open "c:\file.dat" For Input As #1 Len = 32767
    Line Input #1, Line1
    Text1.Text = Line1
    Line Input #1, Line2
    Form1.BackColor = Line2
Close 1
Hope it will help.
 
To do the job properly, use the Registry (through the win32api).

Good luck to you though, because in my experience playing with registry in VB is very annoying...

Martin
 
ok tried both of above
first 1 (seems heck of a complicated to me anyway, but dont take offence me total novice) didnt work kept coming up with errors
like constants fixed length string not allowed as public members of object modules????????

the second one I tried no errors but couldnt tell if it was doing anything
 
Change the reference from Public to Private

Example:
From Public Declare Function to Private Declare Function
AND CHANGE
From Public Const MyINI as string to read only as follows:
Dim MyINI as String

Inside the routine called Form_Load add this line
MyINI = App.Path & "\SomeAppropriateName.ini"
right below the line that reads Dim ReadLine As Integer.

Change the Sub Form_Unload() to read
Sub Form_Unload(Cancel as Integer)

Remember you have to change any code in the sample to refernce existing controls. Example, I have it setting Text1.Text and Text2.Text. Make sure those controls exist or change the code to point to controls that do exist.

It may seem complicated at first but it is actually very easy to use and yes a bit safer then writing to the Registry when you are just starting out. It uses some API calls which accounts for all the referencing at the beginning of the module. Don't get hung up about that code.
It was copied straight out of the API viewer.



Some of the nice things about method 1 is that you do not have to worry about what line your setting resides on inside the ini file, as long as it is under the [SETTINGS] heading. It also has a default setting so that if the line were to be errased accidentally, it will at least use the default setting and the program will run. It resembles the more traditional ini files, in the sense that you can open the ini file and have a fairly good idea as to what setting is what (intuative).

Personally I think the second option Open file may get very complicated because you will have to search for your string with in the text file. The Print Line (for Output) will overwrite the entire file if your not careful and the Append method (if I remember correctly) writes new lines to the file each time so you end up with numerous entries for the same thing. Which one do you choose ? Thus you have to write quite a bit of logic to loop through the file to find the right setting when reading and writing to the file.

It is worth working through any error and playing around with both methods (each has their place) and then when your comfortable, try your hand at the registry.


 
I'd suggest you have a look at SaveSettiong and GetSetting: both of which are built in registry functions, if your settings are going to be user specific.
 
Sorry for not making me to understandable.
Let's try something more understandable and simple.

Create a new form, put 2 CommandButtons (named Command1 and Command2)and 2 text boxes on the form (named Text1 and Text2).

Put the next code into Command1_Click():
Code:
    Open "c:\file.dat" For Output As #1 Len = 32767
            Print #1, Text1.Text
    Close 1
and the next code into Command2_Click()
Code:
    Dim Line1 As String
    Open "c:\file.dat" For Input As #1 Len = 32767
        Line Input #1, Line1
        Text2.Text = Line1
    Close 1

By pressing the command1 button you will create the file and save to the file Text1.text.
By pressing command2 button you will load the line you haved saved into Text2.text (now Text2 will contain the value of Text1 that you have saved into Text2).

If you want to load the value when your program starts put the code from Private Sub Command2_Click() into Private Sub Form_Load().

I do realy think that this is the best solution for you because it consumes less time and resources.
 
Thankyou for that explanation that has helped a lot I know understand what you where explaining and I think it is what I need, but just a few more Questions

1 I take it #1 means number 1 in the file so tex2 could be #2 in the same file?

2 the len Len = 32767 whats that??????
I know understand what you where explaining and I think it is what I need
again thanks
 
Here's a variant that uses the PropertyBag object. Vreat a form with two command buttons, then drop in this code:
[tt]
Option Explicit
Private pb As New PropertyBag

Private Sub Command1_Click()
Dim pbVar As Variant
Dim hFile As Long

' Write properties to propertybag
pb.WriteProperty "Caption", Me.Caption
' And other properties if you like, eg:
pb.WriteProperty "Top", Me.Top
pb.WriteProperty "Left", Me.Left
pbVar = pb.Contents

' Save propertybag contents to a file
hFile = FreeFile
Open "c:\persist.dat" For Binary As hFile
Put hFile, , pbVar
Close hFile

' Now change properties
Me.Caption = "testing"
Me.Left = 100
Me.Top = 100
End Sub

Private Sub Command2_Click()

'Dim Persist As Variant
Dim hFile As Long

' Get the propertybag from file
hFile = FreeFile
Open "c:\persist.dat" For Binary As hFile
Get hFile, , pbVar
Close hFile
pb.Contents = pbVar

' Set properties from saved contents
Me.Caption = pb.ReadProperty("Caption")
Me.Left = pb.ReadProperty("Left")
Me.Top = pb.ReadProperty("Top")

End Sub
 
1. The answer is NO. #1 is the file number so if i am having 2 files it will be more easyer to open them with diferent file numbers.

If you want to save more then one line in a file just use:

Print #1, Text1.Text
Print #1, Text2.text

Let say that text1.text = "first line" and text2.text = "second line" so into the file number 1 it will apear:

first line
second line

and if you want to read those line just type:

dim Line1, Line2 as String
Line Input #1, Line1
Line Input #1, Line2

So Line1 will contain "first line" and Line2 will contain "second line"

2. 32767 is the max lenght of the file in bytes.


For more help, heare is the Open Syntax:

Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]

The Open statement syntax has these parts:

Part * Description

pathname * Required.String expression that specifies a file name — may include directory or folder, and drive.

mode * Required.Keyword specifying the file mode: Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random access.

access * Optional. Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.
lock Optional. Keyword specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.

filenumber * Required. A validfile number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number.

reclength * Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.


Remarks

You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs.

The Len clause is ignored if mode is Binary.

Important In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number.

Do not hesitate to ask more if you have more quiestions.
--------------------------------------------------------
Help it will help
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top