Write to a file?

compugeek

Member
Joined
Aug 21, 2003
Messages
12
Location
USA
I know that with VB you used the Open statement, and the Append type. So, how would I do this same thing in VB.NET? To open a file, create it if it does not exist, and allow it to be written to? Then whats the type for reading the file? Thanks.
 
Use the IO.StreamWriter object to write to the file:
Code:
Dim writer As New IO.StreamWriter("path to the file", True)
First argument is the path to the file, and the second argument which is a boolean indicates whether you want to append to the file.

To open a file and read it use the IO.StreamReader object:
Code:
Dim reader As New IO.StreamReader("path to the file")
then read it using different methods...
reader.ReadLine()
or 
reader.ReadToEnd()
or other reading methods you want to use that you want to use
 
Hey, cool, Ill try that - thanks! If it doesnt work, Ill let ya know, but Im sure it will ;)

EDIT - How do you set the programs current location? In the old VB, it was something like App.Path, but thats probably not the same in .NET.

And how do you actually write to a file? Ive tried writer.WriteLine("Hello") or using a variable: writer.WriteLine(curFunds), but it still is not working... ?
 
Last edited by a moderator:
There is plenty of docs on the net about this stuff.
Do you mean Application.ExecutablePath

C#:
/// <summary>
			/// Writes a text file to disk.
			/// </summary>
			public static void WriteText(string path, object data, bool Append)
			{
				StreamWriter Sw= new StreamWriter(path, Append);
				try
				{
					Sw.Write(data);
				}
				catch{MessageBox.Show("Could not write file.", "Error");}
				Sw.Close();
			}
			//----------			
			public static void WriteText(string path, object o)
			{
				StreamWriter Sw= new StreamWriter(path);
				try
				{
					Sw.Write(o);
				}
				catch{MessageBox.Show("Could not write file.", "Error");}
				Sw.Close();
			}
 
Back
Top