簡體   English   中英

如何使用C#僅從文件名中提取日期

[英]How to extract date only from a file name using C#

我有一種情況,我需要從一般模式為[XXXX_BBBB]_YYYY-MM-DD[.fileExtension]示例Sales_person_2019-05-03.xlsx的文件名中提取日期。

我在 SSIS 腳本任務組件中使用 c# 來實現這一點。

下面是我的代碼:

public void Main()
{

            // TODO: Add your code here
   string pat;
   string date;
   string filename = 'Sales_person_2019-05-03.xlsx'

   // Get the Date part from the file name only
   pat = @"[0-9]{2}[0-9]{2}[0-9]{4}";
   Regex r = new Regex(pat, RegexOptions.IgnoreCase);
   date = r.Match(filename);
   MessageBox.Show(date.ToString());}


    Dts.TaskResult = (int)ScriptResults.Success;
}

但這不起作用。 有人可以幫忙嗎? C# 新手

您可以在沒有正則表達式的情況下實現這一點,只需使用字符串函數( IndexOf()Substring() ):

由於您正在處理固定模式[XXXX_BBBB]_YYYY-MM-DD[.fileExtension] ,只需檢索位於第二個下划線之后的 10 個字符。

public void Main()
{

    string filename = "Sales_person_2019-05-03.xlsx";

    // Get the Date part from the file name only
    string filedate = filename.Substring(filename.IndexOf('_',filename.IndexOf('_') + 1) + 1,10);

    DateTime dt = DateTime.ParseExact(filedate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None)

    Dts.TaskResult = (int)ScriptResults.Success;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM