Solved

Very easy: write to text file

Posted on 2001-07-23
12
155 Views
Last Modified: 2010-05-02
Hi! This one is pretty easy (although rough english)...

How to make a regular textbox, and when you press button "Save" it saves written text from textbox into pre-defined file? So, I want to make simple program when you write something, and press save, and then quit the program, and when you re enter it, it reads automaticly defined file, and enters textbox contents from that file!?

Is that question related to API functions?
Thanks, Daky
0
Comment
Question by:daky
  • 3
  • 3
  • 2
  • +3
12 Comments
 
LVL 6

Expert Comment

by:xSinbad
Comment Utility
To write to a text file you can use this;



Dim varTextBox
Open "Filename" For Output As #1
Write #1, varTextBox
Close #1

To read it again;

Dim varTextBox
Open "Filename" For Input As #1
Input #1, varTextBox
Close #1
0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
First way - using only VB

Open sFileName For Binary As #1
   put #1,,Text1.Text
Close #1

Or you can use FileSystemObject:
'Add referense to Microsoft Scripting Runtime
Private Function WriteTextFile(fName As String, _
  sText As String) As Boolean

  Dim FSO As New FileSystemObject
  Dim FSTR As Scripting.TextStream
  On Error Resume Next
  Set FSTR = FSO.OpenTextFile(fName, ForWriting, _
    Not FSO.FileExists(fName))
  FSTR.Write sText
  WriteTextFile = True
  FSTR.Close
  If Err.Number Then WriteTextFile = False
  On Error GoTo 0
  Set FSTR = Nothing
  Set FSO = Nothing
End Function

' Using
' Private Sub Command2_Click()
'   Dim WriteOK as Boolean
'   WriteOK = WriteTextFile("c:\myfile.txt", Text1.Text)
' End Sub

Cheers
0
 

Expert Comment

by:BlackShark
Comment Utility
Option Explicit
Dim IsDirty As Boolean
Dim strFileName As String
Dim fsoFile As New FileSystemObject
Dim tstFile As TextStream

Private Sub Form_Load()
 strFileName = "c:\test.txt"
 If fsoFile.FileExists(strFileName) Then
    Set tstFile = fsoFile.OpenTextFile(strFileName, ForReading)
    txtText.Text = tstFile.ReadAll
    tstFile.Close
    Set tstFile = Nothing
 Else
    txtText.Text = ""
    fsoFile.CreateTextFile (strFileName)
 End If
 
End Sub

Private Sub txtText_Change()
    IsDirty = True
End Sub

Private Sub cmdSave_Click()
    If IsDirty Then
        Set tstFile = fsoFile.OpenTextFile(strFileName, ForWriting)
        tstFile.Write txtText
        tstFile.Close
        Set tstFile = Nothing
        IsDirty = False
    End If
End Sub

0
 
LVL 1

Author Comment

by:daky
Comment Utility
I tried your, BlackShark, but I must mention that I am using Visual Basic 5! (not 6) and that following code doesn't work for me:

Dim fsoFile As New FileSystemObject
Dim tstFile As TextStream

If there is other way, I will try it! (Now I am gonna try 2 other ways)
0
 
LVL 1

Author Comment

by:daky
Comment Utility
Xsinbad, and Ark:

I get error message on this:

Dim FSO As New FileSystemObject

Xsinbad, please could you tell me where to write you code? (I'm kinda newbie for Visual Basic). This applys for all of you. Thank you.
0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
Hi
You need to add reference to Scriping.
OK, without references (Late Binding)

Private Function WriteTextFile(fName As String, _
 sText As String) As Boolean

 Dim FSO As Object
 Dim FSTR As Object
 On Error Resume Next
 Set FSO = CreateObject("Scripting.FileSystemObject")
 Set FSTR = FSO.OpenTextFile(fName, ForWriting, _
   Not FSO.FileExists(fName))
 FSTR.Write sText
 WriteTextFile = True
 FSTR.Close
 If Err.Number Then WriteTextFile = False
 On Error GoTo 0
 Set FSTR = Nothing
 Set FSO = Nothing
End Function

' Using
' Private Sub Command2_Click()
'   Dim WriteOK as Boolean
'   WriteOK = WriteTextFile("c:\myfile.txt", Text1.Text)
' End Sub

Cheers
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 8

Expert Comment

by:glass_cookie
Comment Utility
Hi!

Here's a file over the net for you:

View code...
http://www.planetsourcecode.com/xq/ASP/txtCodeId.584/lngWId.1/qx/vb/scripts/ShowCode.htm

Descrition: .INI read/write routines

Well, I soppse it works more than just *.ini files.  Since *.ini files are also text files, I suppose it'll work.

That's it!

glass cookie : )
0
 
LVL 6

Expert Comment

by:xSinbad
Comment Utility
Place the first bit of code in the Save buttond On_Click event (rename the save button to "cmdSave" and you text box to txtData;

Private Sub cmdSave_Click()
Dim varTextBox
varTextBox = me.txtData
Open "Filename" For Output As #1
Write #1, varTextBox
Close #1

End Sub

The next bit you would place in the forms On_Open event.

Private Sub Form_Open(Cancel As Integer)
Dim varTextBox
Open "Filename" For Input As #1
Input #1, varTextBox
Close #1
me.txtData = varTextBox
End sub

does that explain it a little better?

Cheers
Marcus

0
 

Expert Comment

by:BlackShark
Comment Utility
As Ark said you must add referense to Microsoft Scripting Runtime (from menu - Project - Referenses.. - in dialog check Microsoft Scripting Runtime) If you don't have it can download it free from http://msdn.microsoft.com/scripting.
If New keyword is not valid for vb5 try:
Dim fsoFile As Object
in Form_Load:
Set fsoFile=CreateObject("Scripting.FileSystemObject")
0
 

Accepted Solution

by:
viklele earned 50 total points
Comment Utility
Your Q is not related to API functions, VB has built-in functions to provide the functionality that you are looking for. Here we go :

On a form, put a textbox (Text1) where you can key-in your stuff, and put a command button (Command1).

Use the following code to store textbox contents to a file c:\temp\demo.txt.

--------------------------------------------------------
Option Explicit

'save contents of text1 to a file
Private Sub Command1_Click()
Dim hFile%

   hFile = FreeFile
   Open "c:\temp\demo.txt" For Output As #hFile
   Print #hFile, Text1.Text
   Close #hFile
   
End Sub

'reload contents at start up
Private Sub Form_Load()
Dim hFile%
Dim sData$

   Text1.Text = ""
   If(Dir$("c:\temp\demo.txt", vbNormal) <> "") then
      hFile = FreeFile
      Open "c:\temp\demo.txt" For Input As #hFile
      Do While Not EOF(hFile)    ' Loop until end of file.
         Input #1, sData
         If (Len(Text1.Text) = 0) Then
            Text1.Text = sData
         Else
            Text1.Text = Text1.Text & vbCrLf & sData
         End If
      Loop
      Close #hFile
   End If

End Sub
--------------------------------------------------------

This should do the trick.
0
 
LVL 1

Author Comment

by:daky
Comment Utility
Thank you all! But, Vikele's answer I must accept. It really works excellent! If you have more you can leave for me. Again, Thank you very much!

Daky!
0
 
LVL 6

Expert Comment

by:xSinbad
Comment Utility
Gee thanks viklele
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.   There is also a companion Debug Toolbar that looks like the followin…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now