3

我有一个带有用户名、用户名、登录和注销时间的文本文件。从这个文本文件中,我需要获取用户 ID 以及该用户在该特定日期登录的次数。我在 Windows 应用程序中使用 C# (.NET) 来做这个。我尝试了这段代码,但我将整个文本放入字符串 strRead 中。在那个 strRead 中,我需要根据日期获取用户登录的计数。

StreamReader strmrdr = new StreamReader("Logfiles.txt");
            string strRead = strmrdr.ReadToEnd();


Username:Rajini||UserId:abc||Userlogintime:10/19/13 12:33:29 PM||UserLogoutTime:10/19/13 12:33:57 PM

Username:Rajini||UserId:abc||Userlogintime:10/19/13 12:35:29 PM||UserLogoutTime:10/19/13 12:36:57 PM
4

4 回答 4

3
int counter = 0;
string line;
string[] words;

System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   words = line.Split("|", StringSplitOptions.RemoveEmptyEntries);
   string userlogintimePart = words[2];
   DateTime loginDate = Convert.ToDate(userlogintimePart.Substring(0, "Userlogintime:".Length));
   if (loginDate > DateTime.Now.AddDays(-1))
      counter++;
   //This is a simple example, but almost everithing in it what you need
   //continue withadd the username into a key value pair
   //if you find again you increment the value by one
}

file.Close();
Console.WriteLine("{0} member logged in from yestoday", counter);
于 2013-10-19T09:15:29.233 回答
2

这并不难,因为您只需要基于日期和用户名的计数,我可能会避开许多尝试完全解析格式的更复杂的解决方案。一个简单的基于正则表达式的解决方案就足够了:

var loginInfo =
    // Read the lines in the file, one by one
    File.ReadLines(args[0])
        // Get a match with appropriate groups for the individual parts
        .Select(l =>
            Regex.Match(l,
                @"Username:(?<username>[^|]+)\|\|
                  UserId:(?<userid>[^|]+)\|\|
                  Userlogintime:(?<date>\S+)", RegexOptions.IgnorePatternWhitespace))
        // Create a new object with the user name and date
        .Select(m => new {
            Username = m.Groups["username"].Value,
            Date = DateTime.Parse(m.Groups["date"].Value, CultureInfo.GetCultureInfo("en-us"))
        })
        // Group by itself, that is, collapse all identical objects into the same group
        .GroupBy(i => i)
        // Create a new object with user name, date and count
        .Select(g => new {
            Username = g.Key.Username,
            Date = g.Key.Date,
            Count = g.Count()
        });

foreach (var info in loginInfo) {
    Console.WriteLine("{0} {1} {2}", info.Username, info.Date, info.Count);
}

对于我来说,这会在稍微扩展的数据集上产生以下输出:

Rajini 2013-10-19 00:00:00 2
Test 2013-10-19 00:00:00 1
Rajini 2013-10-20 00:00:00 1
Test 2013-10-20 00:00:00 3
Rajini 2013-10-21 00:00:00 1
于 2013-10-19T09:45:41.690 回答
0

正如各种人所建议的那样,您应该逐行阅读文件。

对于每一行,您可以将其拆分为 ||。

我建议然后使用用户名和日期的组合作为键来构建字典。每次匹配一个键时,递增该值。

这将根据需要为您提供每个用户每天的登录次数。

于 2013-10-19T09:32:54.440 回答
0

我建议使用StreamReader.ReadLine

在阅读时,您可以增加每天的登录次数。虽然ReadToEnd方法没有错。

您需要在阅读时解析字符串。因为它有分隔符,所以很容易解析。您可以为此使用String.Split方法。

另一个建议可能是将登录计数存储在另一列中,在您写作的每一天。这样阅读起来会更快。

于 2013-10-19T09:22:11.387 回答