Writing a simple text file

phreaky

Well-known member
Joined
Dec 7, 2002
Messages
71
Location
Caracas, Venezuela
I already learn how to read from text files, but what I need to know now is how to write to them and the MSDN doesnt tell about it.

Here it is what Im doing

Dim a As String
Dim sw as IO.StreamWriter
a = "whatever"
IO.File.CreateText("file.txt")
IO.File.OpenWrite("file.txt")
sw.WriteLine(a)
sw.Close()

When I use this code it says that.....

Additional information: The process cannot access the file "(path)\file.txt" because it is being used by another process.
 
heres one method...
Code:
    Private Function SetFileValue(ByVal path As String, ByVal fileName As String, ByVal value As String) As Boolean
        Try
            Dim sb As New System.IO.FileStream(path & "\" & fileName, System.IO.FileMode.OpenOrCreate)
            Dim sw As New System.IO.StreamWriter(sb)
            sw.Write(value)
            sw.Close()
            Return True
        Catch
            Return False
        End Try
    End Function
 
About writing and supplementing...

Ok, now I know how to write a new file but, what if I want to substitute an existing file?, I mean, I have a .TXT file with a simple string, and I want to erase that string and put a new one, well, I mean, I need to rewrite completely a text file.
 
I usually use this code to open a file and write to it, which overwrites the file if its already there.

Obviously, make sure you have the System.IO namespace imported.

Code:
Dim f As StreamWriter

f = New StreamWriter("file.txt", False)
f.WriteLine("blah")
f.Close()
 
Well, I already did try that before, but it doesnt overwrite it completely, because if you had a line that was much more larger than the new one you are trying to overwrite, then it will overwrite until it ends, but it keeps the rest, for example:

if I have a string into the file that says: "my home is green and cute" and then I want to overwrite that string with "my name", then, the file finally records this "my name is green and cute" (that is using the write command), by using the writeline command it will look like:

"my name
is green and cute"

:(

There should be anyway of when you open the file for writing it erases the old one completely and opens it (like a new one), like theres in some other languages.
 
Is this what you want?

Code:
        Dim MyStream As New IO.FileStream("C:\blah.txt", IO.FileMode.Create)
        Dim MyWriter As New IO.StreamWriter(MyStream)
        MyWriter.Write("My Name" & vbCrLf & " is green and cute.")
        MyWriter.Close()
        MyStream.Close()
 
Back
Top