You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用StreamReader从CSV字符串中提取日期并转换格式

Got it, let's walk through how to solve this in C# step by step. Here's a practical approach tailored to your scenario:

Step 1: Read CSV with StreamReader and Target the 8th Field

First, we'll use StreamReader to loop through each line of your CSV. We'll split each line into fields (note: this simple split works for basic CSVs; for complex cases with quoted fields or commas inside values, use a dedicated library like CsvHelper for reliability).

using System;
using System.IO;
using System.Globalization;

class CsvDateProcessor
{
    static void Main(string[] args)
    {
        // Replace with your CSV file path
        string csvFilePath = "your-test-file.csv";
        
        using (StreamReader reader = new StreamReader(csvFilePath))
        {
            string line;
            // Loop through each line in the CSV
            while ((line = reader.ReadLine()) != null)
            {
                string[] fields = line.Split(',');
                
                // Check if there are at least 8 fields (assuming 1-based index; adjust to 8 if using 0-based)
                if (fields.Length >= 8)
                {
                    string targetField = fields[7]; // 8th field (1-based) = index 7 (0-based)
                    
                    // Extract and format the date
                    string extractedDate = ExtractDateSegment(targetField);
                    if (!string.IsNullOrEmpty(extractedDate))
                    {
                        string formattedDate = ConvertToDesiredFormat(extractedDate);
                        // Do something with the formatted date (e.g., log, store)
                        Console.WriteLine($"Formatted date: {formattedDate}");
                    }
                }
            }
        }
    }
Step 2: Extract the Date Substring

Next, we'll pull out the date between the first _ and -1 in your target string. We'll use string indexing to find these markers and grab the middle segment:

private static string ExtractDateSegment(string input)
    {
        // Find the first underscore that precedes the date
        int firstUnderscoreIndex = input.IndexOf('_');
        if (firstUnderscoreIndex == -1)
        {
            Console.WriteLine("No underscore found in the target string.");
            return null;
        }
        
        // Find the "-1" marker that follows the date
        int dashOneIndex = input.IndexOf("-1", firstUnderscoreIndex + 1);
        if (dashOneIndex == -1)
        {
            Console.WriteLine("No '-1' marker found in the target string.");
            return null;
        }
        
        // Calculate the length of the date segment and extract it
        int startIndex = firstUnderscoreIndex + 1;
        int length = dashOneIndex - startIndex;
        return input.Substring(startIndex, length);
    }
Step 3: Convert and Format the Date

Finally, we'll parse the extracted date string (in MM-dd-yyyy format) into a DateTime object, then format it to your desired /MM/dd/yyyy format:

private static string ConvertToDesiredFormat(string dateString)
    {
        // Parse the date using the original format (MM-dd-yyyy)
        if (DateTime.TryParseExact(dateString, "MM-dd-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsedDate))
        {
            // Format to /MM/dd/yyyy (e.g., /01/30/2018)
            return parsedDate.ToString("/MM/dd/yyyy");
        }
        else
        {
            Console.WriteLine($"Failed to parse date: {dateString}");
            return null;
        }
    }
}

Key Notes:

  • CSV Parsing: If your CSV has fields with commas, quotes, or line breaks, replace Split(',') with a library like CsvHelper—it handles edge cases automatically.
  • Index Adjustment: If "8th position" refers to a 0-based index (instead of 1-based), change fields[7] to fields[8].
  • Date Formatting: Use MM for two-digit months (not mm—that's for minutes!) to avoid formatting errors.

内容的提问来源于stack exchange,提问作者mblasco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:18:53