שתף באמצעות


Overwriting a text file with text from a textbox

Question

Friday, April 22, 2016 8:52 PM

Hi, Im looking for help with overwriting a text file called "encrypt me.txt" with the text in a rich text box. So far i have come up with this code here which will create a new file and write to it:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim file As System.IO.StreamWriter
        Dim textoutput As String = TBOUTPUT.Text
        file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/mycomputer/Desktop")
        file.WriteLine(textoutput)
        file.Close()
    End Sub
End Class

However of course i want to overwrite this file which is stored on the desktop (path in code) so any solutions would be much appreciated!

Cheers,

Jake

All replies (14)

Friday, April 22, 2016 9:10 PM ✅Answered | 3 votes

 If you want to overwrite the text file,  then you can use the File.WriteAllText method.  You just need to supply the full path and filename of the text file in the first parameter.  Supply the Text that you want to write to the file in the second parameter.

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        IO.File.WriteAllText("C:\Users\mycomputer\Desktop\TheFileName.txt", TBOUTPUT.Text)
    End Sub

If you say it can`t be done then i`ll try it


Friday, April 22, 2016 9:00 PM

Jake,

Instead of doing it that way, you might consider a StreamReader instead, but I'd encourage you to put it inside a Using block:

Using rdr As New System.IO.StreamReader(filePathHere)
    Do While rdr.Peek() >= 0
        Dim itm As String = rdr.ReadLine.Trim
            'Now process the line “itm”
            Stop
        Loop
End Using

When it gets to "Stop" above, the string "itm" now has the trimmed value of that line. Look at the other ways you can use it which includes reading the entire text rather than line-by-line. If you don't need to test for blank lines, then .ReadToEnd is probably more appropriate.

As an alternate, a very fast way is simply IO.File.ReadAllText, so obviously have several options here.

:)

In the middle of difficulty ... lies opportunity. -- Albert Einstein


Friday, April 22, 2016 9:04 PM | 1 vote

Ahh geez, where's my head!

You're talking about writing, I'm talking about reading!

*****

Use System.IO.File and test for .Exists. If it exists, use IO.File.Delete (you can also do this with a FileInfo instance).

Once that's done, use IO.File.WriteAllText(filePathHere, TextBox1.Text)

...something like that

In the middle of difficulty ... lies opportunity. -- Albert Einstein


Friday, April 22, 2016 9:17 PM

Frank,

hey thanks for the reply, here is the code i have made according to your instructions, when the button is pressed though nothing happens:

 If System.IO.File.Exists("C/users/mycomputer/desktop/ENCRYPT ME.txt") = True Then
            IO.File.Delete("C/users/mycomputer/desktop/ENCRYPT ME.text")
            IO.File.WriteAllText("C/users/mycomputer/desktop/OUTPUT.txt", TBOUTPUT.Text)
        End If

What have i done wrong here?


Friday, April 22, 2016 9:18 PM

Jake,

I just realized that you said that you're using a RichTextBox. It has its own methods and I *think* it will automatically overwrite the target.

Have a look at this:

https://msdn.microsoft.com/en-us/library/ms160336%28v=vs.110%29.aspx

Using that overload, you can elect to save the contents either as an RTF file or a plain text file.

In the middle of difficulty ... lies opportunity. -- Albert Einstein


Friday, April 22, 2016 9:19 PM | 1 vote

Hi, Im looking for help with overwriting a text file called "encrypt me.txt" with the text in a rich text box. So far i have come up with this code here which will create a new file and write to it:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim file As System.IO.StreamWriter
        Dim textoutput As String = TBOUTPUT.Text
        file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/mycomputer/Desktop")
        file.WriteLine(textoutput)
        file.Close()
    End Sub
End Class

However of course i want to overwrite this file which is stored on the desktop (path in code) so any solutions would be much appreciated!

Cheers,

Jake

You can use the My.Computer.FileSystem.WriteAllText Method. Also you need to provide a filename and back slashes are used in VB.Net to separate vol\dir\filename info normally. Somthing like below. False means do not append text to the text file being written to which will cause it to overwrite the text file being written to. You can also use an SaveFileDialog so the user can select the file to write the text to. I'll provide code for that in a minute.

My.Computer.FileSystem.WriteAllText("C:\Users\PlaceUsersNameHere\Desktop\SomeFilename.Txt", TBOUTPUT.Text, False)

Update: Meant SaveFileDialog. Code below.

Option Strict On

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using SFD As New SaveFileDialog
            With SFD
                .Filter = "Text files (*.Txt)|*.Txt"
                .InitialDirectory = "C:\Users\" & Environment.UserName & "\Desktop"
                .AddExtension = True
                .OverwritePrompt = False ' Don't display warning if overwriting file.
            End With
            If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                My.Computer.FileSystem.WriteAllText(SFD.FileName, TextBox1.Text, False)
            End If
        End Using
    End Sub

End Class

You can also use the IO.Path.Combine method for creating a path from multiple strings without the slant bars.

Option Strict On

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Using SFD As New SaveFileDialog
            With SFD
                .Filter = "Text files (*.Txt)|*.Txt"
                .InitialDirectory = IO.Path.Combine("C:", "Users", Environment.UserName, "Desktop")
                .AddExtension = True
                .OverwritePrompt = False ' Don't display warning if overwriting file.
            End With
            If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                My.Computer.FileSystem.WriteAllText(SFD.FileName, TextBox1.Text, False)
            End If
        End Using
    End Sub

End Class

La vida loca


Friday, April 22, 2016 9:21 PM

hey thanks for the reply, here is the code i have made according to your instructions, when the button is pressed though nothing happens:

 If System.IO.File.Exists("C/users/mycomputer/desktop/ENCRYPT ME.txt") = True Then
            IO.File.Delete("C/users/mycomputer/desktop/ENCRYPT ME.text")
            IO.File.WriteAllText("C/users/mycomputer/desktop/OUTPUT.txt", TBOUTPUT.Text)
        End If

What have i done wrong here?

Jake,

Please make it obvious who you're addressing as we don't all see this forum the same way.

*****

First, if you're using an RTB, then look at the .Save method built in but to answer your question, think about what you have there.

IF it exists, then it's deleted and also saved. But if it doesn't exist -- nothing happens!

Take the last statement out of the condition. Delete it if it exists, then save it (either way).

Make sense?

In the middle of difficulty ... lies opportunity. -- Albert Einstein


Friday, April 22, 2016 9:25 PM | 1 vote

 Are you sure that a file named "ENCRYPT ME.txt" is not on your Desktop?  There should be one if this code is being executed.

 You do not need to delete the file if you are overwriting it either.  Also,  if you want to overwrite the file,  then you would use the same filename as the file you want to overwrite,  i am not sure what file that is at this point.

 Test this and see if the MessageBox pops up.  If it does not pop up then you do not have a file on the Desktop named "ENCRYPT ME.txt".

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If IO.File.Exists("C/users/mycomputer/desktop/ENCRYPT ME.txt") Then
            MessageBox.Show("Overwrite File") 'see if this messagebox is shown
            IO.File.WriteAllText("C/users/mycomputer/desktop/ENCRYPT ME.txt", TBOUTPUT.Text)
        End If
    End Sub

If you say it can`t be done then i`ll try it


Friday, April 22, 2016 9:31 PM

Iron,

Ran it and the message box did not pop up and i have checked for a file named "" 

One thing i did notice was this code you submitted did create a new text file: "ENCRYPTME.txt" Would the reason it would not overwrite the original file named "ENCRYPT ME.txt" be due to the space in the name?


Friday, April 22, 2016 9:35 PM

Iron

Aha, it was to do with the space in the name of the original file, when i removed the space the code you gave me originally successfully overwrited it!


Friday, April 22, 2016 9:38 PM

Iron,

Ran it and the message box did not pop up and i have checked for a file named "" 

One thing i did notice was this code you submitted did create a new text file: "ENCRYPTME.txt" Would the reason it would not overwrite the original file named "ENCRYPT ME.txt" be due to the space in the name?

 No, a Space is perfectly fine in the path and filename.  I don`t know if you saw that i edited my post so, read it again if not.  You need a file on the Desktop named "ENCRYPTME.txt" before the code will execute and the messagebox will pop up.

 After you have a file named "ENCRYPTME.txt" on the Desktop,  the code should execute and you will see the messagebox.  The file will be overwritten after you close the messagebox.

 The messagebox line can be removed from the code as soon as you figure out how the code works.

If you say it can`t be done then i`ll try it


Friday, April 22, 2016 9:40 PM | 1 vote

..when i removed the space the code you gave me originally successfully overwrited it!

If you'll use safe a sure methods, spaces in a file's full path (so long as the full path is less than 260 characters) works fine.

For example:

Dim desktop As String = _
    My.Computer.FileSystem.SpecialDirectories.Desktop

Dim exampleFilePath As String = _
    IO.Path.Combine(desktop, "This File Name Can Have Spaces.txt")

In the middle of difficulty ... lies opportunity. -- Albert Einstein


Friday, April 22, 2016 9:41 PM

Try it this way.  If no messagebox pops up,  then the file was overwritten.

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If IO.File.Exists("C/users/mycomputer/desktop/ENCRYPT ME.txt") Then
            IO.File.WriteAllText("C/users/mycomputer/desktop/ENCRYPT ME.txt", TBOUTPUT.Text)
        Else
            MessageBox.Show("There is no file on the Desktop named ENCRYPT ME.txt")
        End If
    End Sub

If you say it can`t be done then i`ll try it


Friday, April 22, 2016 9:46 PM | 1 vote

Hi, Im looking for help with overwriting a text file called "encrypt me.txt" with the text in a rich text box. So far i have come up with this code here which will create a new file and write to it:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim file As System.IO.StreamWriter
        Dim textoutput As String = TBOUTPUT.Text
        file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/mycomputer/Desktop")
        file.WriteLine(textoutput)
        file.Close()
    End Sub
End Class

However of course i want to overwrite this file which is stored on the desktop (path in code) so any solutions would be much appreciated!

Cheers,

Jake

Your title says TextBox but your post has rich text box in it. If it is a RichTextBox and you have formatting or images in it then you probably want to save the RichTextBox.RTF rather than RichTextBox.Text since the RTF, when loaded back into a RichTextBox will have the formatting and/or images in it. By formatting I mean different fonts for different words or letters and different forecolors/backcolors for text and such.

La vida loca