简体   繁体   English

如何不覆盖 VB.net 中的文件

[英]How not to overwrite files in VB.net

I want to check if the current file exists at the same time save video to different file but it only overwrites to an existing file.我想检查当前文件是否存在,同时将视频保存到不同的文件,但它只会覆盖现有文件。

Here is my code:这是我的代码:

Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) Handles ButtonVIDEO.Click

    f = New Filters
    cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
    cap.PreviewWindow = PictureBox1
    Dim Filename As String = "c:\\folder\MyFile"
    Dim i As Integer = 0
    Dim extension As String = ".mp4"

    If ButtonVIDEO.BackColor = Color.Black Then
        cap.Filename = Filename + extension

        If File.Exists(Filename) Then
            Do
                i = i + 1
            Loop While File.Exists(Filename + i.ToString() + extension)
            Filename = Filename + i.ToString()
        End If

        cap.Cue()
        cap.Start()
        ButtonVIDEO.BackColor = Color.Red
        ButtonVIDEO.Text = "PLAYING"
        ButtonPHOTO.Hide()



    End If
End Sub

You are assigning the file name to cap before searching for an unsused file name.在搜索未使用的文件名之前,您将文件名分配给cap Also, there is an error in your logic, as you are creating the full file name with Filename + i.ToString() + extension but you also append i to Filename itself with Filename = Filename + i.ToString() .此外,您的逻辑中存在错误,因为您使用Filename + i.ToString() + extension创建完整文件名,但您还使用Filename = Filename + i.ToString()i附加到Filename本身。 So, in then end, you are appending the number twice.因此,最后,您将数字附加两次。

Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) _
    Handles ButtonVIDEO.Click

    Dim Filename As String = "c:\folder\MyFile"
    Dim i As Integer = 0
    Dim extension As String = ".mp4"
    Dim path As String = Filename & extension

    f = New Filters
    cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
    cap.PreviewWindow = PictureBox1

    If ButtonVIDEO.BackColor = Color.Black Then
        If File.Exists(path) Then
            Do
                i = i + 1
                path = Filename & i & extension
            Loop While File.Exists(path)
        End If

        cap.Filename = path
        cap.Cue()
        cap.Start()
        ButtonVIDEO.BackColor = Color.Red
        ButtonVIDEO.Text = "PLAYING"
        ButtonPHOTO.Hide()
    End If
End Sub

The path should have only one backslash in c:\\folder .路径在c:\\folder应该只有一个反斜杠。 In VB strings are concatenated with & , not + .在 VB 中,字符串与&连接,而不是+

See answer to The difference between + and & for joining strings in VB.NET请参阅在 VB.NET 中连接字符串的 + 和 & 之间的区别的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM