Simple Q - How to create a file

Posted on 2002-07-25
Last Modified: 2010-05-18
I want to Create a simple text file
Add a Line into it
read a line from it
and save the file to the HD.
Please give an example code in VB
(with or w/o using COM Objetcs).
Question by:TheShark8
LVL 28

Expert Comment

ID: 7177095
This will create a text .If it does exist it will be overwritten:

Open "C:\somefile.txt" for output as #1
Print #1,"Hello,this will print on line 1"
Print #1,"Hello,this will print on line 2"
Close #1

This will also create a text file,but will add to the file if it exists:

Open "C:\somefile.txt" for append as #1
Print #1,"Hello,this will print on line 1"
Close #1

To read from the file 1 line at a time:
Open "C:\somefile.txt" for input as #1
Do Until eof(1)
Line input #1 G$
Msgbox G$
Close #1

The #1 represents the open file.If you were to 2 files at once,you could use #2 for the second file. If you are working with alot of files you could use 'FreeFile' to get the next available file#.
LVL 28

Accepted Solution

vinnyd79 earned 20 total points
ID: 7177112
when you read the file there should be a "," after line input #1 in the above example.

Open "C:\somefile.txt" for input as #1
Do Until eof(1)
Line input #1, G$
Msgbox G$
Close #1


Expert Comment

ID: 7177118
You can also use filesystemobjects in VB.  There should be examples in help files

e.g.  to create a file and write data use something like

Sub CreateFile()
   Dim fso, tf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set tf = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line with a newline character.
   tf.WriteLine("Testing 1, 2, 3.")
   ' Write three newline characters to the file.        
   ' Write a line.
   tf.Write ("This is a test.")
End Sub

For reding a line

Sub ReadFiles
   Dim fso, f1, ts, s
   Const ForReading = 1
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line.
   Response.Write "Writing file <br>"
   f1.WriteLine "Hello World"
   ' Read the contents of the file.
   Response.Write "Reading file <br>"
   Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)
   s = ts.ReadLine
   Response.Write "File contents = '" & s & "'"
End Sub
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.


Expert Comment

ID: 7177207
vinnyd79 has suggested using Freefile with "lots of files". I strongly recommend using FreeFile all the time. It's just that it's easy to get into the habit of Open ... as #1 and when you start say, sharing code amongst projects, then you could run into trouble. Also, this way you don't have to track which number to use next and you can use sensible indentifier names for the file channels.

   Dim EmployeeFile as Integer
   EmployeeFile = FreeFile()
   Open ... For Input As #EmployeeFile
   Close #EmployeeFile

Not a rule, just a suggestion! :-)

(Note you can't use the # with the EOF function. It's EOF(EmployeeFile) as correctly written by vinnyd79).
LVL 44

Expert Comment

ID: 7177252
be aware the Open ... for OUTPUT will wipeout an exiting instance of the named file, before creating a NEW file of that name.  If you want to keep any exiting file, and be able to append to it,  then use Open... FOR APPEND

that will create a NEW file if the named file DOES NOT ALREADY exit, but will open an exiting file of that name, and allow your code to add records onto the end.

Just a note.

Arthur Wood

Expert Comment

ID: 7177262
//to save data
open "c:\test.txt" for output as #1
print #1,"test line1"
print #1,"test line2"
close #1
//to read all data
open "c:\test.txt" for input as #1
do while not eof(1)
input #1,thechars
list1.additem thechars
close #1
- you can use the freefile as mentioned above to get the first free file handle
- you can open the file as binary to get binary data
- you can use the put and get method to read data by records.


Expert Comment

ID: 7178060
I sincerely recommend to use Scripting object for better file management.

  Dim fso, ts
  Set fso = CreateObject("Scripting.FileSystemObject")

  ' where ts is TextStream Object
  Set ts = fso.CreateTextFile(app.path & "\myfile.txt", True)

  ' Write a line with a newline character.
  ts.WriteLine("DATA   A   B  C  D")

'for reading a  file
  Set ts = fso.OpenTextFile(app.path "\myfile.txt", ForReading)
  do until ts.AtEndofFile
    s = ts.ReadLine
    msgbox s

set fso = nothing
LVL 28

Expert Comment

ID: 7178285
I would sincerely recommend NOT using the scripting object for something that can be done with VB's native I/O functions. Not to mention that you basically proposed an answer that has already been suggested by Damienm.

Expert Comment

ID: 7522817
Dear prakashbitra
I've rejected your proposed answer as Experts Exchange holds an experiment to work without the answer button.

See: <>
Paragraph: Site Update for Wednesday, November 06, 2002

By this rejection the Asker will be notified by mail and hopefully he will take his responsibility to finalize the question or post an additional comment.
The Asker sees a button beside every post which says "Accept This Comment As Answer" (including rejected answers) -- so if he/she thinks yours is the best, you'll be awarded the points and the grade.

EXPERTS: I will return in seven days to close this question.
Please leave your thoughts and recommendations here


Thanks !

Experts Exchange Moderator
LVL 49

Expert Comment

ID: 8040620
Hi TheShark8,
It appears that you have forgotten this question. I will ask Community Support to close it unless you finalize it within 7 days. I will ask a Community Support Moderator to:

    Accept vinnyd79's comment(s) as an answer.

TheShark8, if you think your question was not answered at all or if you need help, just post a new comment here; Community Support will help you.  DO NOT accept this comment as an answer.

EXPERTS: If you disagree with that recommendation, please post an explanatory comment.
DanRollins -- EE database cleanup volunteer

Expert Comment

ID: 8095673
per recommendation

Community Support Moderator @Experts Exchange

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Restricting text box entry from \/:?<>"| 9 86
MS Access - Capture pressed key onclick 4 33
TT Auto Dashboard 13 92
which modules are active in VB6 project? 6 12
Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
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…

809 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