如何自动删除驱动器中的文件d:如果创建时间> 30天vb.net

时间:2018-03-08 10:13:19

标签: vb.net

我想制作一个程序,自动删除驱动器中的文件d:如果文件超过30天,我进行搜索,我发现我可以比较文件的创建时间和日期,我尝试下面的代码但它不起作用。

我在驱动器d中的文件是2018年3月7日,我将我的计算机日期更改为2018年4月10日,因此它将超过30天,但它不起作用。
我的表格中有2个按钮,第一个是选择要删除的文件夹的路径。第二个按钮是设置30天后它将自动删除数据。

我的代码请帮助纠正错误的地方。我是vb.net的新手。

Imports System
Imports System.IO
Imports System.Text

Public Class DeleteByDay

    Private Sub btnDeleteDay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteDay.Click
        If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtPath.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSet.Click
       Dim eachFileInMydirectory As New DirectoryInfo(txtPath.Text)
       Dim fileName As IO.FileInfo

       Try
           For Each fileName In eachFileInMydirectory.GetFiles
               If fileName.Extension.Equals("*.spi") AndAlso
                  (Now - fileName.CreationTime).Days > 30 Then

                   fileName.Delete()
               End If
           Next
        Catch ex As Exception
            MessageBox.Show("No Files older than 90 days exists be deleted " & ex.Message)
        End Try
    End Sub

End Class 

2 个答案:

答案 0 :(得分:0)

fileName似乎只有文件名。您需要完整的删除路径。

Dim eachFileInMydirectory As New DirectoryInfo("C:\MyFolder")
Dim fileName As IO.FileInfo

For Each fileName In eachFileInMydirectory.GetFiles
    If fileName.Extension.Equals(".txt") AndAlso (Now - fileName.CreationTime).Days > 8 Then
        Dim fullPath As String = Path.Combine("C:\MyFolder", fileName.ToString)
        File.Delete(fullPath)
    End If
Next

答案 1 :(得分:0)

您的代码似乎有效,因此必定会出现其他问题。

我假设“btnDeleteDay”有理由选择目录,“btnSet”进行删除,但名称似乎与其功能不匹配。

如果没有要删除的文件会抛出异常的前提是错误的 - 您可能会认为这是一个错误,但是代码没有任何错误。

您可以向代码添加更多检查,以便它告诉您是否存在没有删除文件的原因。此外,您可以过滤DirectotyInfo.GetFiles检索的文件,因此无需检查扩展名。

不要担心使用额外的变量来使代码看起来非常简单:简单的代码通常很容易维护。

我根据您展示的内容提出了以下代码,并且有一个小方法来创建一些文件进行测试:

Private Sub btnSelectDirectory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectDirectory.Click
    FolderBrowserDialog1.SelectedPath = "C:\temp" ' for testing

    If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        txtPath.Text = FolderBrowserDialog1.SelectedPath
    End If

End Sub

Private Sub btnDeleteOldFiles_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteOldFiles.Click
    Dim dir = txtPath.Text

    Dim directoryToProcess As New DirectoryInfo(dir)
    Dim fileExtension = ".spi"

    Dim filesToProcess = directoryToProcess.GetFiles("*" & fileExtension)
    Dim nFilesDeleted = 0

    If filesToProcess.Count > 0 Then
        For Each fileName As IO.FileInfo In filesToProcess
            Dim fileAge = DateTime.Now - fileName.CreationTime

            If fileAge > TimeSpan.FromDays(30) Then
                Try
                    fileName.Delete()
                    nFilesDeleted += 1
                Catch ex As Exception
                    MessageBox.Show("Failed to delete file." & vbCrLf & ex.Message, IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath), MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End Try
            End If

        Next

        If nFilesDeleted = 0 Then
            MessageBox.Show(String.Format( "No {0} file older than 90 days exists be deleted.",fileExtension))
        End If

    Else
        MessageBox.Show(String.Format($"There are no {0} files in directory {1}.", fileExtension, dir))

    End If

End Sub

Private Sub bnMakeSampleFiles_Click(sender As Object, e As EventArgs) Handles bnMakeSampleFiles.Click
    ' sub to create test data
    Dim dest = "C:\temp"

    For i = 1 To 10
        Dim fName = Path.Combine(dest, i.ToString() & ".spi")
        File.WriteAllText(fName, i.ToString())
        Dim fi = New FileInfo(fName)
        fi.CreationTime = DateTime.Now - TimeSpan.FromDays(25 + i)
    Next

End Sub