簡體   English   中英

如何拒絕替換 txt 文件請求,並讓他們創建新的 txt 文件?

[英]What to do to reject a replace txt file request, and offer them to create new txt file instead?

使用這些代碼,我不知道出了什么問題,我仍然無法解決我的問題

請檢查並糾正我。 怎么了?

我想要的是當他們單擊保存文件按鈕時,保存文件對話框將顯示將數據保存到文件中。 如果他們嘗試替換現有文件,Msgbox 將顯示拒絕他們的替換請求。 所以他們必須創建新文件。

使用此代碼,這就是正在發生的事情。

第一次單擊,您可以創建或替換而不會收到拒絕消息框。

第二次單擊,您將收到拒絕創建或替換。

第三次點擊就像第一次點擊

第四次點擊就像第二次點擊

等等。

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

這與我的第一篇文章有關, How to WriteAllText but restrict to overwrite the existing file?

像這樣,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM