删除部分取消的复制文件VB.NET

时间:2016-03-19 02:02:33

标签: .net vb.net file stream file-copying

删除在复制过程中被取消的文件的最佳方法是什么?我做的是如果我点击Cancel按钮将启用Timer并检查文件是否存在,如果是,则它将删除该文件,然后计时器将被禁用,反之亦然。这是我的代码:

Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
    Timer3.Enabled = True 
End Sub

updatedFilesList(Of String),其中包含在复制之前放置的文件。

Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer3.Tick
    Dim dest As String = Label6.Text
        For i = 0 To updatedFilesCancel.Count - 1
             File.Delete(Path.Combine(dest, updatedFilesCancel(i)))
             Timer3.Enabled = False
        Next
End Sub

Timer有1秒。间隔,它成功删除 ONCE ,第二次它不再工作,似乎是什么问题?建议?

1 个答案:

答案 0 :(得分:1)

我建议你使用 Task CancellationTokenSource ,而不是弄乱计时器,它会让你更好地控制和文件复制操作的行为。

我在一个名为 FileCopy 的简单类中实现了所有这些,用于演示一个示例。

https://github.com/ElektroStudios/ElektroKit/blob/master/Solution/v1.2/Elektro.IO/Types/FileCopy.vb

如果您不喜欢它,您可以获取源代码并根据您的需要进行调整,或者只是看看我的源代码中的内容是如何通过您自己来管理的。

一个例子:

Imports Elektro.IO.Types

Public Class Form1 : Inherits Form

    Friend WithEvents FileCopier As FileCopy
    Private fileCopyCancelToken As CancellationTokenSource

    Private Sub ButtonStart_Click() Handles Button1.Click

        Me.FileCopier = New FileCopy("C:\Source File.ext")

        ' It returns a CancellationTokenSource to cancel the task whenever you want.
        Me.fileCopyCancelToken = Me.FileCopier.CopyTo("C:\Target file.ext",
                                                      overwrite:=True,
                                                      deleteFileOnCancel:=True,
                                                      cancelCallback:=Nothing)

    End Sub

    Private Sub ButtonCancel_Click() Handles Button2.Click

        Me.fileCopyCancelToken.Cancel()

    End Sub

    Private Sub FileCopier_ProgressChanged(ByVal sender As Object, ByVal e As FileCopyProgressChangedEventArgs) _
    Handles FileCopier.FileCopyProgressChanged

        Console.WriteLine(String.Format("Copied: {0:0.00}%", e.Percentage))

    End Sub

End Class

可以在源代码中找到另一个(更加扩展的)示例:

Public Class Form1 : Inherits Form

    Friend WithEvents FileCopier As FileCopy
    Private fileCopyCancelToken As CancellationTokenSource

    Private Sub Button1_Click() Handles Button1.Click

        Me.StartCopy()

    End Sub

    Private Sub Button2_Click() Handles Button2.Click

        Me.CancelCopy()

    End Sub

    Private Sub StartCopy()

        ' Create a dummy file of 2 GB
        Using fs As New FileStream("C:\source file.ext", FileMode.CreateNew)
            fs.SetLength(2147483648)
        End Using

        Me.FileCopier = New FileCopy("C:\source file.ext")

        Me.fileCopyCancelToken =
            Me.FileCopier.CopyTo("C:\Target file.ext",
                                 bufferSize:=(CInt(Me.FileCopier.File.Length \ (1024 * 100)) + 1),
                                 overwrite:=True,
                                 deleteFileOnCancel:=False,
                                 cancelCallback:=AddressOf Me.FileCopier_CancelCallBack)

    End Sub

    Private Sub CancelCopy()

        ' Cancel the current file-copy operation.
        Me.FileCopier.CancelCopy(Me.fileCopyCancelToken)

    End Sub

    ''' <summary>
    ''' Callback that is called when the a file-copy operaton of the <see cref="FileCopier"/> is cancelled.
    ''' </summary>
    Private Sub FileCopier_CancelCallBack()

        Me.Invoke(
            Sub()
                Me.Label1.Text = "Canceled!"
                Me.Label2.Text = "Canceled!"
                Me.Label3.Text = "Canceled!"
                Me.Label4.Text = "Canceled!"
            End Sub)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Handles the <see cref="FileCopy.FileCopyProgressChanged"/> event of the <see cref="FileCopier"/> instance.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="sender">
    ''' The source of the event.
    ''' </param>
    ''' 
    ''' <param name="e">
    ''' The <see cref="FileCopyProgressChangedEventArgs"/> instance containing the event data.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    Private Sub FileCopier_FileCopyProgressChanged(ByVal sender As Object, ByVal e As FileCopyProgressChangedEventArgs) _
    Handles FileCopier.FileCopyProgressChanged

        Me.Invoke(
            Sub()
                Me.Label1.Text = String.Format("Size: {0} MB", (e.Filesize / 1024).ToString("n2"))
                Me.Label2.Text = String.Format("Written: {0} MB", (e.BytesRead / 1024).ToString("n2"))
                Me.Label3.Text = String.Format("Read: {0} MB", (e.BytesRemaining / 1024).ToString("n2"))
                Me.Label4.Text = String.Format("Done: {0}%", e.Percentage.ToString("n2"))
            End Sub)

    End Sub

End Class

我希望这可以帮到你。