C# 在循环结束时调整正在读取的文件名,而不中断循环

C# 在循环结束时调整正在读取的文件名,而不中断循环,c#,date,increment,C#,Date,Increment,每天结束时生成2份报告。我希望能够在每个月底对它们进行分析 每个文件中都有大约一千行长ASCII字符串。这已成功编码,但一次只能提取一个文件并对其执行分析 我将尝试输入下面代码的相关结构。。我希望这足以让你知道需要做什么。如果不是的话,我很乐意发布整个事情 using (StreamReader reader = new StreamReader("YYYYMMDD----1234D.dat")) { while loop //this goes through all the lines in

每天结束时生成2份报告。我希望能够在每个月底对它们进行分析

每个文件中都有大约一千行长ASCII字符串。这已成功编码,但一次只能提取一个文件并对其执行分析

我将尝试输入下面代码的相关结构。。我希望这足以让你知道需要做什么。如果不是的话,我很乐意发布整个事情

using (StreamReader reader = new StreamReader("YYYYMMDD----1234D.dat"))
{
while loop //this goes through all the lines in the file. 
{if //if meets certain criteria then store into a list, otherwise ignore

}
foreach // this part does the analysis of all the values in the list, totals, etc

第一个报告采用上述格式,另一个报告使用不同的数字代替1234D(为了便于讨论,为5678D,所以:yyyymmdd---5678D)。这两个数字始终不变

我希望能够将每个文件中的所有数据存储到我的列表中,然后对整个月执行分析,而不是每天进行细分,因此它将循环遍历每个文件,当它到达文件末尾时,将名称增加一天,循环遍历,等等。(或查找所有具有一个月X的文件-以更好的为准)。这将填充列表,然后foreach将执行其分析和输出。预计我会将所有必需的文件放入与程序当前使用的文件夹相同的文件夹中

当前代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;

class Program 
{
    public class EntryLine
    {
        public int I { get; set; }
        public string LineStart { get; set; }
        public string Letters { get; set; }
        public int TVolume { get; set; }
        public long TPrice { get; set; }
        public double MVolume { get; set; }
        public string Currency { get; set; }
        public string DateTime {get; set; }

    }

    static void Main(string[] args)
    {
        List<EntryLine> myList = new List<EntryLine>();
        int i = 1;
        using (StreamReader reader = new StreamReader("20121203----1234D.dat"))
        {
            string line;
            var locations = new Dictionary<string, int[]>() {
            {"210", new [] {405, 4, 128, 12, 141, 12, 247, 15, 121, 3}}, 
            {"310", new [] {321, 4, 112, 12, 125, 12, 230, 15, 105, 3}}, 
            {"410", new [] {477, 4, 112, 12, 125, 12, 360, 15, 105, 3}} 
        };

            while ((line = reader.ReadLine()) != null)
            {
                var lineStart = line.Substring(0, 3);

                if (lineStart == "210" || lineStart == "310" || lineStart == "410")
                {
                    var currentLocations = locations[lineStart];
                    var letters = line.Substring(currentLocations[0], currentLocations[1]);

                    var tvolume =
                        int.Parse(line.Substring(currentLocations[2], currentLocations[3])) +
                        int.Parse(line.Substring(currentLocations[4], currentLocations[5]));

                    var tprice = long.Parse(line.Substring(currentLocations[6], currentLocations[7]));
                    var mvolume = tprice * tvolume * 0.01 * 0.0000001;
                    var currency = line.Substring(currentLocations[8], currentLocations[9]);

                    myList.Add(new EntryLine()
                    {
                        I = i,
                        LineStart = lineStart,
                        Letters = letters,
                        TVolume = tvolume,
                        TPrice = tprice,
                        MVolume = mvolume,
                        Currency = currency
                    });
                    i = i + 1;
                }
            }

            var x = myList.GroupBy(g => new { g.Letters, g.Currency })
                .Select(a => new { a.Key.Letters, a.Key.Currency, TSum = a.Sum(s => s.TVolume), MSum = a.Sum(s => s.MVolume) });

            foreach (var item in x)
            {
                Console.WriteLine("{0} currency: {1} tvolume: {2} mVolume: {3}", item.Letters, item.Currency, item.TSum, item.MSum);
            }
        } Console.ReadLine();
    }

}
使用系统;
使用System.Collections.Generic;
使用System.IO;
使用系统文本;
使用System.Text.RegularExpressions;
使用System.Linq;
班级计划
{
公共级入口线
{
公共整数I{get;set;}
公共字符串LineStart{get;set;}
公共字符串字母{get;set;}
公共int TVolume{get;set;}
公共长TPrice{get;set;}
公共双MVolume{get;set;}
公共字符串货币{get;set;}
公共字符串日期时间{get;set;}
}
静态void Main(字符串[]参数)
{
List myList=新列表();
int i=1;
使用(StreamReader=新StreamReader(“20121203---1234D.dat”))
{
弦线;
var locations=newdictionary(){
{“210”,新[{405,4,128,12,141,12,247,15,121,3},
{“310”,新[{321,4112,1215,1230,15105,3},
{“410”,新[{477、4112、12512、12360、15105、3}}
};
而((line=reader.ReadLine())!=null)
{
var lineStart=line.Substring(0,3);
如果(lineStart==“210”| | lineStart==“310”| | lineStart==“410”)
{
var currentLocations=位置[lineStart];
变量字母=行。子字符串(currentLocations[0],currentLocations[1]);
变量体积=
int.Parse(line.Substring(currentLocations[2],currentLocations[3]))+
int.Parse(line.Substring(currentLocations[4],currentLocations[5]);
var tprice=long.Parse(line.Substring(currentLocations[6],currentLocations[7]);
var mvolume=tprice*tvolume*0.01*0.0000001;
var currency=line.Substring(currentLocations[8],currentLocations[9]);
添加(新的EntryLine())
{
I=I,
LineStart=LineStart,
字母=字母,
TVolume=TVolume,
TPrice=TPrice,
MVolume=MVolume,
货币=货币
});
i=i+1;
}
}
var x=myList.GroupBy(g=>new{g.Letters,g.Currency})
.Select(a=>new{a.Key.Letters,a.Key.Currency,TSum=a.Sum(s=>s.TVolume),MSum=a.Sum(s=>s.MVolume)});
foreach(x中的变量项)
{
Console.WriteLine(“{0}货币:{1}tvolume:{2}mVolume:{3}”,item.Letters,item.currency,item.TSum,item.MSum);
}
}Console.ReadLine();
}
}

如果您只需将
foreach
using
块中移出,那么就不会阻止您使用第二个文件名复制
using
块,或者将
using
块放在您将文件名传递到的自己循环中:

string[] filenames = new string[] {
    "20121203 ----1234D.dat",
    "20121204 ----1234D.dat",
    "20121205 ----1234D.dat" };
List<Whatever> yourListOfMatchingItems = new List<Whatever>();

foreach (string filename in filenames)
{
    using (StreamReader reader = new StreamReader(filename))
    {
        while (/* whatever you had before */)
        {
            if (/* whatever you had before */)
            {
            }
        }
    }
}
foreach (/* item in your list */)
{
}
string[]文件名=新字符串[]{
“20121203---1234D.dat”,
“20121204---1234D.dat”,
“20121205---1234D.dat”};
List yourListOfMatchingItems=新建列表();
foreach(文件名中的字符串文件名)
{
使用(StreamReader=新StreamReader(文件名))
{
而(/*你以前拥有的一切*/)
{
如果(/*你以前拥有的一切*/)
{
}
}
}
}
foreach(/*列表中的项目*/)
{
}

您需要动态创建文件名,而不是对其进行硬编码。然后您可以在所有文件中循环生成值列表,然后对其进行处理

为什么不把它分成几个方法呢?比如:

public void Process()
{
    // logic to get string[] of filenames here. You could loop through each
    // day you need a list for and generate a filename for the given day
    var values = new List<T>();
    foreach (var filename in filenames)
    {
        var valuesFromFile = GetValuesFrom(filename);
        values.AddRange(valuesFromFile);
    }
    ProcessValues(values);
}

private List<T> GetValuesFrom(string filename)
{
    var values = new List<T>();
    while loop //this goes through all the lines in the file. 
    {if //if meets certain criteria then store into a list, otherwise ignore
    }
    return values;
}

private void ProcessValues(List<T> values)
{
    foreach // this part does the analysis of all the values in the list, totals, etc
}
公共作废流程()
{
//在这里获取文件名字符串[]的逻辑。您可以循环每个字符串
//您需要为给定日期创建列表并生成文件名的日期
var值=新列表();
foreach(文件名中的var文件名)
{
var valuesFromFile=GetValuesFrom(文件名);
values.AddRange(valuesFromFile);
}
过程值(值);
}
私有列表GetValuesFrom(字符串文件名)
{
var值=新列表();
while loop//这将遍历文件中的所有行。
{如果//如果满足某些条件,则将其存储到列表中,否则忽略
}
返回值;
}
私有void进程值(列表值)
{
foreach//此部分分析列表中的所有值、总计等
}

T当然是你的值的类型

T有很多方法
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ReportAnalysis {
static class Program {
    static void Main() {
        //lets run the analysis for Nov, 2012

        //First, read in all report files, and store relevant lines
        var reportInfo = ReportAnalyzer.ReadFiles(2012, 11);

        //Now analyze all files at once
        ReportAnalyzer.RunAnalysis(reportInfo);
    }
}
class ReportAnalyzer {
    struct ReportFile {
        public string Path;
        public DateTime Date;
        public List<string> Lines;
    }

    public static IList<ReportFile> ReadFiles(int year, int month) {
        //Put names of files here.
        string[] fileNames = new string[] { "{0:YYYYMMDD}----1234D.dat", "{0:YYYYMMDD}----5678D.dat" };

        DateTime dateStart = new DateTime(year, month, 1); //start of month
        DateTime dateEnd = dateStart.AddMonths(1); //start of NEXT month (i.e. 1 day past end of this month)

        var reportList = new List<ReportFile>();

        DateTime date = dateStart;
        while (date < dateEnd) {  //we don't actually get to dateEnd, just the day before it.
            foreach (var fileTemplate in fileNames) {
                //insert the date in YYYYMMDD format
                var file = string.Format(fileTemplate, date);
                if (File.Exists(file)) {
                    var report = new ReportFile() {
                        Date = date,
                        Path = file,
                        Lines = GetReportLines(file)
                    };
                    reportList.Add(report);
                }
            }
            //now jump to next day
            date = date.AddDays(1);
        }
        return reportList;
    }

    private static List<string> GetReportLines(string file) {
        var lines = new List<string>();
        try {
            using (StreamReader reader = new StreamReader(file)) {
                while (!reader.EndOfStream) {
                    var line = reader.ReadLine();
                    if (true /* insert criteria */)
                        lines.Add(line);
                }
            }
        } catch (Exception ex) {
            //log the error however you see fit
            lines.Add(string.Format("ERROR Could not open report file {0}: {1}", file, ex.Message));
        }
        return lines;
    }

    public static void RunAnalysis(IList<ReportFile> reports) {
        foreach (var r in reports) {
            //Do whatever analysis you need
            Console.WriteLine(r.Date);
            Console.WriteLine(r.Path);
            foreach (var line in r.Lines)
                Console.WriteLine(line);
        }
    }
}
}
void ProcessReports {
    string[] fileNames = new string[] { "{0:YYYYMMDD}----1234D.dat", "{0:YYYYMMDD}----5678D.dat" };
    DateTime dateStart = new DateTime(year, month, 1); //start of month
    DateTime dateEnd = dateStart.AddMonths(1); //start of NEXT month (i.e. 1 day past end of this month)
    List<string> lines = new List<string>();
    DateTime date = dateStart;
    while (date < dateEnd) {  //we don't actually get to dateEnd, just the day before it.
        foreach (var fileTemplate in fileNames) {
            //insert the date in YYYYMMDD format
            var file = string.Format(fileTemplate, date);
            if (File.Exists(file)) {
                using (StreamReader reader = new StreamReader(file)) {
                    while (!reader.EndOfStream) {
                        var line = reader.ReadLine();
                        if (true /* insert criteria */)
                            lines.Add(line);
                    }
                }
            }
        }
        //now jump to next day
        date = date.AddDays(1);
    }   
    //Now we have all the lines. Let's process them;
    foreach (var line in lines) {
        //do something with the report lines
    }
}