按自定义模式

时间:2017-04-05 16:08:05

标签: vb.net

我将有很多文件进入我的服务器,并且必须检查文件名是否符合约定的约定。我正在寻找一种检查某些模式的方法。例如:

SIR 2016-12.xlsx
Silnik_5_30_cos_26122017.xlsx
DIDO 24_05_2017.xlsx
OMO 12-30.csv
MOK 5_3_17.csv
'others unknown file naming conventions at the moment

据我所知,动态部分将始终是每个文件的日期(差异可能与日期/日期时间/时间的格式有关)。我认为我需要的是拥有一个配置文件,并使用括号为动态日期/日期时间/时间声明每个文件的预期模式,如下所示:

'within <> are dynamic part

    RTO TR <YYYY-MM>.xlsx           
    Engine-FR_<YYYY_MM_DD>.csv      
    SIR <YYYY-MM>.xlsx
    Silnik_5_30_cos_<DDMMYYYY>.xlsx
    DIDO <DD_MM_YYYY>.xlsx
    OMO <hh-mm>.csv
    MOK <d_M_YY>.csv

后缀具有“通用检查器”,可以检查/解码特定的传入文件名,并查看它是否符合约定的约定。你能提出什么建议以及如何实现这一目标。举例赞赏。如果可能,不使用正则表达式。请注意,我不知道所有不同的传入文件,因为它将在项目步骤中出现,因此可以为新文件名打开解决方案。

1 个答案:

答案 0 :(得分:0)

您可以使用DateTime.TryParseExact检查特定的日期格式,格式可以包含其他字符。您可以使用它来检查文件名格式。

为此,您需要创建一个描述有效格式的DateTime Custom Format Strings数组。您可能需要用单引号括住预期格式的非日期部分,以避免将它们视为格式字符(例如,避免将“MOK”中的“M”视为“月份”格式字符

以下代码创建一个包含两个示例格式的数组。有两个功能:

  • 如果您只想知道是否使用ValidateFormat功能 filename匹配任何有效格式。
  • 如果您需要知道文件名匹配的哪种有效格式,请使用FindFormat功能。

两个函数都返回在文件名中找到的日期。

私人格式()As String = {“'SIR'yyyy-MM'.xlsx'”,“'MOK'd_M_yy'bu.csv'”,“Ala”,“'BRT-GH'yyyy-MM” }

''' <summary>Check whether an input string is in one of the valid formats</summary>
''' <param name="input">The string to be checked</param>
''' <param name="dt">If the function returns True, this variable contains the date and time from the input string</param>
''' <returns>True if the input string matches any of the expected formats</returns>
Function ValidateFormat(input As String, ByRef dt As DateTime) As Boolean
    Return DateTime.TryParseExact(TextBox1.Text, formats, 
                                  Globalization.CultureInfo.CurrentCulture,
                                  Globalization.DateTimeStyles.None, dt)
End Function

''' <summary>Find which of the valid formats is matched by the input string</summary>
''' <param name="input">The string to be checked</param>
''' <param name="dt">If the function returns True, this variable contains the date and time from the input string</param>
''' <returns>True if the input string matches any of the expected formats</returns>
Function FindFormat(input As String, ByRef dt As DateTime) As String
    For Each format As String In formats
        If DateTime.TryParseExact(TextBox1.Text, format, 
                                  Globalization.CultureInfo.CurrentCulture,
                                  Globalization.DateTimeStyles.None, dt) Then Return format
    Next
    Return ""
End Function

<强> [编辑] 作为如何使用这些函数的示例,以下是我用来测试它们的方法。他们都假设您在TextBox1中输入要检查的文件名,并在TextBox2中显示结果。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim dt As DateTime
    TextBox2.Text = If(ValidateFormat(TextBox1.Text, dt), dt.ToString, "Error")
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim dt As DateTime
    TextBox2.Text = FindFormat(TextBox1.Text, dt)
End Sub
相关问题