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
This is related to my first post, How to WriteAllText but restrict to overwrite the existing file?
CodePudding user response:
Like this,
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