# Visual Basic > Visual Basic .NET > VS 2010 How to WriteAllText but restrict to overwrite the existing file?

## maxtertj

The AppendAllText can append into existing file and can create a file if no file exist. the WriteAllText can Write into new created file and overwrite the existing file.

I'm trying to find another alltext for what I want to happen.

What I want to do is to save my textboxcontent.text into txt file. I want to save 3 different content that will be displayed into my textboxcontent.text And I only have one button.

That one button will open savefiledialog but with the code I have, I can only do 2 things, Write and Append.

Now, This is what suppose to happen.

*If I save the textcontent.text to an existing txt file, it will prompt message box "Do you want to overwrite this file?" And even if I click Yes, it will not allow to.
I must be able to create new txt file since I was not able to overwrite the file.
The reason is because I don't want to delete or overwrite the existing file with important information saved in it.

I hope somebody can help me.

This is the code I have.



```
Imports System.io
Private lastSaveFileName As String = String.Empty
Private Function GetSaveFileName3(ByVal suggestedName As String) As String
    Using sfd3 As New SaveFileDialog()
        sfd3.Filter = "Text Files (*.txt) |*.txt"
        sfd3.FileName = suggestedName
        sfd3.OverwritePrompt = True


        If DialogResult.OK Then

        End If
        If sfd3.ShowDialog() = DialogResult.OK Then
            MessageBox.Show(
            Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
            "Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
        )
        Else


        End If
        Return String.Empty
    End Using
    
End Function
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
    lastSaveFileName = GetSaveFileName3(lastSaveFileName)
    If Not String.IsNullOrEmpty(lastSaveFileName) Then
        File.AppendAllText(lastSaveFileName, TextContent.Text)
    End If
```

----------


## schoemr

Max,

If I look at your previous question and now this one then I get the idea you did not figure out exactly what you want to do.

You can ask to overwrite and even when the user clicks YES it should NOT do it? 

Perhaps what you need to do is take a pen and paper and go sit and design a flow diagram of what exactly it is you want to do - forget about the programming. 

That is maybe the most important step. Once you know exactly what you want then we can look at how to achieve that..

----------


## techgnome

TL;DR -> OP wants to save data to NEW files only and don't allow the user to overwrite existing files.


Typically when I've seen this behavior, it's making backups. In which case I'm not given the option to put in a file name. It just creates one with its own format - usually the date in some format.

I have mixed feelings about this. If I'm selecting an existing file, and you give me the prompt to overwrite it, and I do, and I loose important info ... that's on me. Case in point, I moved things off my machine to an external HD ... a couple of those files included some CAD-style files of something I spent months working on. Once I re-built the machine, I moved everything off the external drive that I needed. At some point I wiped the HDD... so that I could use it for future backups. I recently went back in to the CAD-style program ... opend up that file... went to another one... when it crashed. When I restarted it, it cvame back up with file 2 I was looking at, asked if I want to restore it back to disk ... I said yes... it prompted me to overwrite ........ and that's when I noticed I had accidentally saved it back to file1! Months of work gone... so now I'm having to go through the pains of re-creating it again. Users are going to use... and if you prompt someone "overwrite file?" and they say YES and you don't ... especially w/o telling them ... now that's on you.


-tg

----------


## sapator

Instead of taking the whole system into your hands (that, granted, it can be done and I have done it in the past) you may want to take a look at log4net.
You can break your categories to INFO,WARNING,ERROR etc and you can choose a size that after reached it will create a new file.
I'm writing this as from what I understand, this is not for educational purposes but for a real app, so that's a more secure way of logging data.

P.S. Credit to JMC as a few years back reminded me of this solution.

----------


## maxtertj

> Max,
> 
> If I look at your previous question and now this one then I get the idea you did not figure out exactly what you want to do.
> 
> You can ask to overwrite and even when the user clicks YES it should NOT do it? 
> 
> Perhaps what you need to do is take a pen and paper and go sit and design a flow diagram of what exactly it is you want to do - forget about the programming. 
> 
> That is maybe the most important step. Once you know exactly what you want then we can look at how to achieve that..


Maybe you just missed the scenario I'm talking about. Maybe you did not encounter it in life yet. But let me add an update.

----------


## maxtertj

This is what I've done so far.

I tried to use the File.Exist but I don't know where to place it to make it run in the way I wanted.

Please see this code and help me fix it.
This code is running well in almost the way I want. I'm missing something.


```
    Imports System.IO
    Private lastSaveFileName As String = String.Empty

    Private Sub SaveFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveFile.Click
        If Not File.Exists(lastSaveFileName) Then
            lastSaveFileName = GetSaveFileName(lastSaveFileName)
            If Not String.IsNullOrEmpty(lastSaveFileName) Then
                File.WriteAllText(lastSaveFileName, txtdisplay1.Text)
            End If
        ElseIf File.Exists(lastSaveFileName) Then
            lastSaveFileName = GetSaveFileName2(lastSaveFileName)
            If Not String.IsNullOrEmpty(lastSaveFileName) Then
                File.WriteAllText(lastSaveFileName, txtdisplay1.Text)
            End If
        End If

        
    End Sub

    Private Function GetSaveFileName2(ByVal suggestedName As String) As String
        Using sfd As New SaveFileDialog()
            sfd.Filter = "Text Files (*.txt) |*.txt"
            sfd.FileName = suggestedName
            sfd.OverwritePrompt = True

            If sfd.ShowDialog() = DialogResult.OK Then
                'If File.Exists(lastSaveFileName) Then
                MessageBox.Show(
           Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
           "Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
       )   
            End If  
            Return String.Empty
        End Using
    End Function
    
    Private Function GetSaveFileName(ByVal suggestedName As String) As String
        Using sfd As New SaveFileDialog()
            sfd.Filter = "Text Files (*.txt) |*.txt"
            sfd.FileName = suggestedName
            sfd.OverwritePrompt = True

            If sfd.ShowDialog() = DialogResult.OK Then
                Return sfd.FileName
            End If
            Return String.Empty
        End Using
    End Function
```

With this code, I was able to save the textdisplay to a txtfile but it's like, it's bypassing the Elseif function.

Sometimes, poeple forgot to avoid important files and accidentally deleted it. This is what I'm preventing to happen.

I let the overwriteprompt true to let it ask the user if they want to replace. It accidentally click the yes, this will show message "This file have records from your last session, Please create new file to save new records." means that even the user want to replace it, the program will not allow it. I don't want to remove that scenario.

(Scenario 1)
What happen in this code is this, when I click the button, savefiledialog pop up and giving me choice how I want to save the textdisplay. 
I can create new file or replace existing file.
First, I choose to replace, and a messagebox shows and saying, I can't replace the file. 
Then I create new file, it lets me save the txt display normally.
That's what I want.

(scenario 2)
 The code runs that way at first, but if you click the button again, and try to create new file first, the message box will show saying I can't replace the file. then when I choose to replace, no message box shows and the file was replace. I lost the file.

That's where I need help. I only want the Scenario 1.
Please try on your own I you don't get what I mean.

----------


## maxtertj

> TL;DR -> OP wants to save data to NEW files only and don't allow the user to overwrite existing files.
> 
> 
> Typically when I've seen this behavior, it's making backups. In which case I'm not given the option to put in a file name. It just creates one with its own format - usually the date in some format.
> 
> I have mixed feelings about this. If I'm selecting an existing file, and you give me the prompt to overwrite it, and I do, and I loose important info ... that's on me. Case in point, I moved things off my machine to an external HD ... a couple of those files included some CAD-style files of something I spent months working on. Once I re-built the machine, I moved everything off the external drive that I needed. At some point I wiped the HDD... so that I could use it for future backups. I recently went back in to the CAD-style program ... opend up that file... went to another one... when it crashed. When I restarted it, it cvame back up with file 2 I was looking at, asked if I want to restore it back to disk ... I said yes... it prompted me to overwrite ........ and that's when I noticed I had accidentally saved it back to file1! Months of work gone... so now I'm having to go through the pains of re-creating it again. Users are going to use... and if you prompt someone "overwrite file?" and they say YES and you don't ... especially w/o telling them ... now that's on you.
> 
> 
> -tg


Yes. You see, we sometimes forget important files and accidentally delete it. That's what I'm trying to prevent in my experiment program. 
" If I'm selecting an existing file, and you give me the prompt to overwrite it, and I do, and I loose important info " That's what I'm thinking too. 
"I noticed I had accidentally saved it back to file1! Months of work gone...I'm having to go through the pains of re-creating it again" This is what I don't want to happen.
That's why I'm trying to solve this problem with the help of all who knows.

----------


## schoemr

I understand perfectly well that sometimes you don't want to overwrite a file. But that was not your requirement at first. But okay I don't want to sound like some other Ogres here  :Smilie:  

If you don't want to overwrite a file then don't ask! You can disable the prompt  to overwrite AND if there is already a file with that name force the user to type a new file name.. 

Is that want you want? If yes, then that's easy I can help.

Btw: you say in #6





> (scenario 2)
> That's what I want.


And then the next paragraph:




> I only want the Scenario 1

----------


## schoemr

> Months of work gone


That must have hurt  :Smilie:  I suppose you didn't have a backup of the backup?

It reminds me... Once I restored a database from a USB backup forgetting to backup the current one. Maybe forget is not the right word. If didn't think it was necessary. After the restore I then realized that the current database had information in still needed...

----------


## techgnome

Here's what you do:
1) Turn off the overwrite prompt in the dialog ...
2) Prompt the user to save the file.
3) if the user selects OK, then check to see if the file exists.
4) If it does, tell the user that hte file already exists and to select a different filename; return to step 2
5) If the file does not exist... write to it.


-tg

----------


## maxtertj

> I understand perfectly well that sometimes you don't want to overwrite a file. But that was not your requirement at first. But okay I don't want to sound like some other Ogres here  
> 
> If you don't want to overwrite a file then don't ask! You can disable the prompt  to overwrite AND if there is already a file with that name force the user to type a new file name.. 
> 
> Is that want you want? If yes, then that's easy I can help.
> 
> Btw: you say in #6
> 
> 
> ...





> But okay I don't want to sound like some other Ogres here


No worries, I don't hear you like that. I'm new and I need honest opinions.

Thanks for this idea. I will try this one. This helps. 



> if there is already a file with that name force the user to type a new file name..


I'll update again after.

When typing, the Scenario 1 and 2 was in one paragraph and I just split then into two and add the (Scenario) hehe forgot to include that word in Scenario 1. But thanks you found it. I corrected it.

----------


## maxtertj

> Here's what you do:
> 1) Turn off the overwrite prompt in the dialog ...
> 2) Prompt the user to save the file.
> 3) if the user selects OK, then check to see if the file exists.
> 4) If it does, tell the user that hte file already exists and to select a different filename; return to step 2
> 5) If the file does not exist... write to it.
> 
> 
> -tg


I'll try. Thank you.

I'll update again.

----------


## techgnome

In the future, it helps if you describe what it is you want - Not HOW you're trying to do it, but concentrate on the WHAT. 

HOW: (Scenario 1)
What happen in this code is this, when I click the button, savefiledialog pop up and giving me choice how I want to save the textdisplay.
I can create new file or replace existing file.
First, I choose to replace, and a messagebox shows and saying, I can't replace the file.
Then I create new file, it lets me save the txt display normally.
That's what I want.

(scenario 2)
The code runs that way at first, but if you click the button again, and try to create new file first, the message box will show saying I can't replace the file. then when I choose to replace, no message box shows and the file was replace. I lost the file.

WHAT: Prompt the user to save the data to a file ... but if that file already exists, warn them and ask for another file name.


The moment you introduce controls and their types... you're getting into the how. Notice there's none of that in mine. That's because it's the WHAT and nothing more. 

Now, once you've got the WHAT distilled, you can provide the HOW so that we can see what you've tried and might be able to explain why it's not working. It also prevents someone form posting something and you going "it doesn't work. Already tried that." 

-tg

----------


## maxtertj

Using this codes, I don't know what's wrong, I still can't solve my problem

Please check and correct me.
What's wrong?

What I want is when they click the savefile button, savefiledialog will show to save the data to a file. If they try to replace an existing file, Msgbox will show to reject their replace request. So they have to create new file.

With this code, this is what's happening.
1st click, you can create or replace without getting reject messagebox.
2nd click, you will receive rejection either you create or replace.
3rd click is like the 1st click
4th click is like the 2nd click
And so on.






```
Private lastSaveFileName As String = String.Empty
Private Sub SaveFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveFile.Click
        lastSaveFileName = GetSaveFileName2(lastSaveFileName)
        If Not String.IsNullOrEmpty(lastSaveFileName) Then
            File.AppendAllText(lastSaveFileName, txtdisplay1.Text)
        End If


    End Sub

    Private Function GetSaveFileName2(ByVal suggestedName As String) As String
       
            Using sfd3 As New SaveFileDialog()
                sfd3.Filter = "Text Files (*.txt) |*.txt"
                sfd3.FileName = suggestedName
            sfd3.OverwritePrompt = False


            If sfd3.ShowDialog() = DialogResult.OK Then
                If Not File.Exists(lastSaveFileName) Then
                    MessageBox.Show(
                Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
                "Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
            )
                Else
                    Return sfd3.FileName
                End If

                
            Else


            End If

                Return String.Empty
            End Using


    End Function
```

----------


## maxtertj

> In the future, it helps if you describe what it is you want - Not HOW you're trying to do it, but concentrate on the WHAT. 
> 
> 
> WHAT: Prompt the user to save the data to a file ... but if that file already exists, warn them and ask for another file name.
> 
> 
> The moment you introduce controls and their types... you're getting into the how. Notice there's none of that in mine. That's because it's the WHAT and nothing more. 
> 
> Now, once you've got the WHAT distilled, you can provide the HOW so that we can see what you've tried and might be able to explain why it's not working. It also prevents someone form posting something and you going "it doesn't work. Already tried that." 
> ...


Thank you for the addvice.

----------


## maxtertj

> Instead of taking the whole system into your hands (that, granted, it can be done and I have done it in the past) you may want to take a look at log4net.
> You can break your categories to INFO,WARNING,ERROR etc and you can choose a size that after reached it will create a new file.
> I'm writing this as from what I understand, this is not for educational purposes but for a real app, so that's a more secure way of logging data.
> 
> P.S. Credit to JMC as a few years back reminded me of this solution.


I will study about this.

----------


## schoemr

Hi try this



```
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
    Dim saveFileDialog1 As New SaveFileDialog()
    saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True

    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        If File.Exists(saveFileDialog1.FileName) Then
            MessageBox.Show("A file with that name already exists. Please select a different file name or choose a different location to save the file.")
        Else
            File.WriteAllText(saveFileDialog1.FileName, TextBox1.Text)
        End If
    End If
End Sub
```

You can also disable the overwrite prompt for extra measure



```
saveFileDialog1.OverwritePrompt = False
```

----------


## maxtertj

> Hi try this
> 
> 
> 
> ```
> Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
>     Dim saveFileDialog1 As New SaveFileDialog()
>     saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
>     saveFileDialog1.FilterIndex = 2
> ...


Yes! Finally, you got it. Thank you, your code works the way I want.
I need to study your code. 
I don't know yet this "FilterIndex", "RestoreDirectory".

Also, This code also do the same task.



```
Private Function GetSaveFileName2(suggestedName As String) As String
    Dim rv As String = String.Empty 'String.Empty is do not save
    Dim sfd3 As New SaveFileDialog()
    sfd3.Filter = "Text Files (*.txt) |*.txt"
    sfd3.FileName = suggestedName
    sfd3.OverwritePrompt = False
    Dim dr As DialogResult
    Do
        dr = sfd3.ShowDialog
        If dr = DialogResult.OK Then
            If IO.File.Exists(sfd3.FileName) Then
                MessageBox.Show("Not saved! .... Please create new file to save new records or Cancel to Exit.",
                                    "Save error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                rv = sfd3.FileName
            End If
        End If
    Loop While dr = Windows.Forms.DialogResult.OK AndAlso rv = String.Empty
    Return rv
End Function
```

cto: dbasnett

----------


## .paul.

> saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
> saveFileDialog1.FilterIndex = 2


@schoemr made a mistake there. Index of 2 doesnt exist in the Filter line

Text files index = 0
All files index = 1

Passing a FilterIndex of 2, defaults to 0

----------


## .paul.

https://learn.microsoft.com/en-us/do...owsdesktop-7.0

----------


## schoemr

> @schoemr made a mistake there. Index of 2 doesnt exist in the Filter line
> 
> Text files index = 0
> All files index = 1
> 
> Passing a FilterIndex of 2, defaults to 0



Hi Paul,

Thank you for the correction  :Smilie:

----------


## .paul.

> Hi Paul,
> 
> Thank you for the correction


No problem...

----------

