Tuesday, March 18, 2008

Writing to Files

In order to write to files, you will have to create a StreamWriter. Here is an example:

Dim sw As IO.StreamWriter
sw = IO.File.CreateText("newfilename.txt")
sw.WriteLine("This will go in the new file")
sw.Close()

If you use CreateText as shown above, then the file in quotes will be created and ready for use. If the file existed before you opened it, the file contents will be deleted, even if nothing is writen to the file. If you just want to place the new text at the end of the existing file, you can use AppendText() instead of CreateText().

Another thing you should know, is that the text will not be written to the file unless you Close() the file.

If you simply place the name of the file in quotes without an absolute path, then the file will be saved in the MyDocuments\Visual Studio 2005\Projects\[project name]\[project name]\bin\Debug folder, where [project name] is the name of your project.

No comments: