简体   繁体   English

C#-从多个文件解析年/月,运行程序并在子文件夹(年/月)中创建新文件

[英]C# - Parse Year/Month from multiple files, run program and create new file in subfolders (year/month)

I currently have a program where I am taking existing log files from a directory, running through each one and calculating statistics, then creating a new file from that. 我目前有一个程序,我要从目录中获取现有日志文件,逐个运行并计算统计信息,然后从该目录创建一个新文件。

The log files are currently named as such: 2012-4-24.log 日志文件的当前名称如下:2012-4-24.log

Upon creation of the new statistics file, it keeps similar formatting but adds "-Stats": 2012-4-24-Stats.log 创建新的统计信息文件后,它会保持类似的格式,但会添加“ -Stats”:2012-4-24-Stats.log

Here is what I am trying to solve: I want to create new directories for each year, and month, that way I can have a folder structure as follows: 这是我要解决的问题:我想为每年和每月创建新目录,这样我就可以拥有如下文件夹结构:

DailyStatistics -> 2012 -> 4 -> 2012-4-24-Stats.log DailyStatistics-> 2012-> 4-> 2012-4-24-Stats.log

DailyStatistics -> 2012 -> 5 -> 2012-5-1-Stats.log DailyStatistics-> 2012-> 5-> 2012-5-1-Stats.log

etc, etc 等等

I am not sure how to parse the year and month from the filename, and then run through all files with that same year and month, then have my program go through my loop to create the actual files. 我不确定如何从文件名解析年份和月份,然后遍历具有相同年份和月份的所有文件,然后让我的程序遍历循环以创建实际文件。

Here is the code I have... 这是我的代码...

class Processor
{
    public void ProcessDailyLogFiles()
    {
        foreach (string fullFileName in Directory.GetFiles(Settings.LogPath))
        {
            string fileName = Path.GetFileNameWithoutExtension(fullFileName);
            new DailyReader().CalculateStatistics(fileName);
            new DailyReader().MoveLogFile(fileName);
        }

    }
}

next class... 下课...

public void CalculateStatistics(string filename)
    {
        string path = Settings.DailyPath;

        if (!path.EndsWith(@"\"))
            path = path + @"\";

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        string tempFileName = Settings.LogPath + filename + ".log";
        string destFileName = path + filename + "-Stats.log";

        var statistics = File.ReadLines(tempFileName)
        .Where(line => line.StartsWith("Process"))
        .Select(line => line.Split('\t'))
        .GroupBy(items => items[1])
        .Select(g =>
        new
        {
            Division = g.Key,
            ZipFiles = g.Sum(i => Convert.ToInt32(i[4])),
            Conversions = g.Sum(i => Convert.ToInt32(i[5])),
            ReturnedFiles = g.Sum(i => Convert.ToInt32(i[6])),
            TotalEmails = g.Sum(i => Convert.ToInt32(i[7]))
        });

        Log myLog = new Log(destFileName);
        statistics
           .ToList()
           .ForEach(d => myLog.Write(d.Division, d.ZipFiles, d.Conversions, d.ReturnedFiles, d.TotalEmails));
        //Add error handlers
        myLog.Close();
    }

final log class... 最终日志类...

#region Member Variables

    StreamWriter dailyStats;

    #endregion

    public Log(string filename)
    {
        this.Open(filename);
    }

    #region Public Static Functions

    public void Open(string tempFileName)
    {
        var sb = new StringBuilder();

        if (!File.Exists(tempFileName))
        {
            dailyStats = File.AppendText(tempFileName);
            sb.Append("Division");
            sb.Append("\t");
            sb.Append("Zip Files");
            sb.Append("\t");
            sb.Append("Conversions");
            sb.Append("\t");
            sb.Append("Returned Files");
            sb.Append("\t");
            sb.Append("Total E-Mails");
            sb.Append("\t");
            dailyStats.WriteLine(sb.ToString());
        }
        else
        {
            dailyStats = new StreamWriter(tempFileName);
        }
    }


    public void Write(string division,
                             int zipFiles, int conversions, int returnedFiles, int totalEmails)
    {

        var sb = new StringBuilder();

        if (writeLog)
        {
            sb.Append(division);
            sb.Append("\t");
            sb.Append(zipFiles);
            sb.Append("\t");
            sb.Append(conversions);
            sb.Append("\t");
            sb.Append(returnedFiles);
            sb.Append("\t");
            sb.Append(totalEmails);
            sb.Append("\t");
            dailyStats.WriteLine(sb.ToString());
        }
    }

    public void Close()
    { 
        dailyStats.Close();
    }
}

Thanks guys 多谢你们

  String filename = "2012-4-24.log";
  String file = Path.GetFileNameWithoutExtension(filename);
  String[] parts = file.Split('-');
  if (parts.Length == 3)
  {
    String year = parts[0];
    String month = parts[1];
    String day = parts[2];

    Console.WriteLine(string.Format("year:{0} - month:{1} - day:{2}", year, month, day));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM