C# 在txt文件中搜索日期

C# 在txt文件中搜索日期,c#,console-application,C#,Console Application,我正在做一个约会程序,其中我根据日期添加了几个约会,并存储在一个文本文件中。根据输入的日期显示约会详细信息时出现问题。文本文件中存储的约会如下所示 日期和时间:2013年8月8日上午9:30人员姓名:Shiv 日期和时间:2013年8月8日上午10:30人员姓名:桑杰 日期和时间:2013年8月10日晚上9:30人员姓名:库马尔 问题是,当我输入任何日期来搜索约会时,假设该特定日期有2个约会,我的输出仅显示一个约会 示例:如果我输入日期为2013年8月8日,则输入日期的文本文件中存储了两个约会,

我正在做一个约会程序,其中我根据日期添加了几个约会,并存储在一个文本文件中。根据输入的日期显示约会详细信息时出现问题。文本文件中存储的约会如下所示

日期和时间:2013年8月8日上午9:30人员姓名:Shiv

日期和时间:2013年8月8日上午10:30人员姓名:桑杰

日期和时间:2013年8月10日晚上9:30人员姓名:库马尔

问题是,当我输入任何日期来搜索约会时,假设该特定日期有2个约会,我的输出仅显示一个约会

示例:如果我输入日期为2013年8月8日,则输入日期的文本文件中存储了两个约会,但我的输出仅显示一个类似这样的约会

预约详情

2013年8月8日上午9:30人员姓名:Shiv

我的代码:

Console.WriteLine("Enter the date to search appointment in (dd/mm/yyyy) format");
string Date = Console.ReadLine();

string str = sr.ReadToEnd();

bool isDate = File.ReadAllText("E:\\Practice/C#/MySchedular.txt").Contains(Date) ? true : false;

if (isDate)        
{             
    string searchWithinThis = str; ;

    int CharacterPos = searchWithinThis.IndexOf(Date);      

    sr.BaseStream.Seek(CharacterPos ,SeekOrigin.Begin);

    str = sr.ReadLine();

    Console.WriteLine("\n*********Appointment Details*********");

    Console.WriteLine("{0}", str);

    Console.WriteLine("\n");    
}            
else        
{           
    Console.WriteLine("No appointment details found for the entered date");        
}

也许这样的方法会奏效:

static void Main(string[] args)
{
    string filename = @"E:\Practice\C#\MySchedular.txt";
    string fileContent;
    Console.WriteLine("Enter the date to search appointment in (dd/mm/yyyy) format");
    string date = Console.ReadLine();

    using (StreamReader sr = new StreamReader(filename))
    {
        fileContent = sr.ReadToEnd();
    }

    if (fileContent.Contains(date))
    {
        string[] apts = fileContent.Split('\n').Where(x => x.Contains(date)).ToArray();

        foreach (string apt in apts)
        {
            Console.WriteLine("\n**Appointment Details**");
            Console.WriteLine("{0}", apt);
            Console.WriteLine("\n");
        }
    }
    else
    {
        Console.WriteLine("No appointment details found for the entered date");
    }
    Console.Read();
}

看起来您正在移动到文本文件中的行首并读取一行。因此,即使有多行具有所需的日期字符串,也不会读取它们。您应该检查给定日期内多个事件的发生情况,并进行相应的读取。顺便说一下,正则表达式可能是另一种方法(可能更快、更可靠、更灵活)。