从文件名变量解析String到Date

时间:2015-07-22 16:32:26

标签: vb.net parsing

目的是移动指定文件夹中的文件,如果日期至少是今天的一天。我在移动文件时遇到了一些麻烦,因为我没有看到它存档。我假设它正在从文件名中解析日期。 VS2005 .Net 2.0

Sub CopytoArchive(ByVal mydirpath)
    'mydirpath = "C:\UTResults\"
    'T:\UTResults\Press3\sv70206655\data07012015.txt is an example of txtFileList
    Dim txtFileList As String() = Directory.GetFiles(mydirpath, "*.txt", SearchOption.AllDirectories) 'Search all files in the given path with .txt type

    For Each txtName As String In txtFileList
        Dim pressname As String = txtName.Substring(0, txtName.LastIndexOf("\")) 'take out the file extension
        pressname = pressname.Substring(0, pressname.LastIndexOf("\")) 'take out the folder after the press folder for a clean "PRESS" look
        pressname = pressname.Remove(0, 13)

        Dim folderexists As String = Path.Combine("C:\writetest\", pressname)

        Dim filename = txtName.Remove(0, 4)
        filename = filename.Substring(0, filename.LastIndexOf("."))
        filename = Convert.ToDateTime(filename)

        If filename < Date.Now Then
            If My.Computer.FileSystem.DirectoryExists(folderexists) Then
                My.Computer.FileSystem.MoveFile(txtName, folderexists)
            Else
                My.Computer.FileSystem.CreateDirectory(folderexists)
                My.Computer.FileSystem.MoveFile(txtName, folderexists)
            End If
        End If
    Next
End Sub

2 个答案:

答案 0 :(得分:2)

Sub CopytoArchive(ByVal mydirpath As String)
    'mydirpath = "C:\UTResults\"
    'T:\UTResults\Press3\sv70206655\data07012015.txt is an example of txtFileList

    Dim dir As New DirectoryInfo(mydirpath)
    Dim fileInfos = dir.EnumerateFiles("*.txt", SearchOption.AllDirectories)
    fileInfos = fileInfos.
       Where(Function(fi) DateTime.ParseExact(RegEx.Replace(fi.Name, "[^0-9]", ""), "MMddyyyy", Nothing) < DateTime.Now.AddDays(-1))
      'The magic is here ------^^^

    For Each info In fileInfos
        Dim pressname As String = _ 
         Path.GetDirectoryName(info.DirectoryName).Replace(mydirpath, "C:\writetest\")

        'Better/more efficient to just call CreateDirectory() every time
        My.Computer.FileSystem.CreateDirectory(pressname)
        My.Computer.FileSystem.MoveFile(info.FullName, pressname)
    Next
End Sub

答案 1 :(得分:0)

日期字符串通常是个问题,这是基本方法:

    Dim s As String = "data07012015.txt"
    s = s.Substring(4)
    s = s.Substring(0, s.LastIndexOf("."))

    ' convert to valid en date string
    s = s.Insert(2, "/").Insert(5, "/")

    Dim dt As Date = s
    If dt < Now.AddDays(-1) Then
        Stop
    Else
        Stop
    End If