Не считает файлы в статистику - C#
Формулировка задачи:
Даны 4 файла-лога с несколькими строками записей.
нужно чтобы программа выгрузила содержимое,пропарсила файлы и на выходе создала 3 отчёта по пользователям,трафику и сайтам.(Всё это с использованием потоков)
Программа запускается,но увы он в файлы-отчёты ничего не записывает.
Пошагово прошелся компилятором,везде null.
Может утечка данных,не в ту переменную присваиваю может быть.
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Text; using System.IO; using System.Diagnostics.Eventing.Reader; using System.Threading.Tasks; namespace Лабораторная_2 { class countFiles { string[] filelist = Directory.GetFiles(@"D:\logfiles", "*.txt"); public string user { get; set; } public string adres { get; set; } public int trafik { get; set; } public string data { get; set; } public countFiles(string userr="", string adress="", int traffic=0) { user = userr; adres = adress; trafik = traffic; } public void parsingfiles(string lline) { List<countFiles> list = new List<countFiles>(); //здесь будет результат for (int i = 1; i < filelist.Length; i++) { if (filelist[i] == "") continue; string[] lineParts = filelist[i].Split(' '); list.Add(new countFiles(lineParts[0], lineParts[1], int.Parse(lineParts[2]))); } } public void ReadFile(string filename) { using (StreamReader sr = new StreamReader(filename)) { string line; while ((line = sr.ReadLine()) != null) { parsingfiles(list); } } } } class StatLog { public Dictionary<String, UInt64> userstat; public Dictionary<String, UInt64> adrestat; public Dictionary<int, UInt64> trafikstat; public StatLog()//конструктор { userstat = new Dictionary<String, UInt64>(); adrestat = new Dictionary<String, UInt64>(); trafikstat = new Dictionary<int, UInt64>(); } public StatLog createStat(StatLog info)// { UInt64 value; foreach (var item in info.userstat) { userstat[item.Key] = (userstat.TryGetValue(item.Key, out value) ? value : 0) + item.Value; } foreach (var item in info.adrestat) { adrestat[item.Key.Trim()] = (adrestat.TryGetValue(item.Key.Trim(), out value) ? value : 0) + item.Value; } foreach (var item in info.trafikstat) { trafikstat[item.Key] = (trafikstat.TryGetValue(item.Key, out value) ? value : 0) + item.Value; } return this; } } class Program { public static System.Collections.Generic.List<StatLog> m_threadResult;//результат выполнения потока public static Queue<String> m_workFiles = new Queue<String>();//очередь файлов с каталога public static bool m_iscomplete = false;//флаг завершения ввода public static readonly object m_locker = new object(); //мьютекс для работы с файлами выводимых в очередь public void injected(String filelist)//выгрузка файлов в очередь для обработки { if (!Directory.Exists(filelist)) { return; } lock (m_locker) { foreach (var x in Directory.EnumerateFiles(filelist)) { m_workFiles.Enqueue(x); } } m_iscomplete = true;//установить флаг завершения } public static StatLog processFile(String file)//обработка файла { if (!File.Exists(file))///Проверка на наличие файла в каталоге { return new StatLog(); } StreamReader sr = System.IO.File.OpenText(file); String line; StatLog sc = new StatLog();// countFiles cnt = new countFiles(); while ((line = sr.ReadLine()) != null) { cnt.parsingfiles(line); } return sc; } static public void threadFunc(int id) { String value; StatLog localStat = m_threadResult[id]; StatLog sc = new StatLog(); while (true) { lock (m_locker) { if (m_workFiles.Count < 1) { if (m_iscomplete) { break; } continue; } value = m_workFiles.Dequeue();//получение первого файла из очереди с удалением его из очереди } var filestat = processFile(value);//обработать файл localStat.createStat(filestat);//объеденить статистику } } static void Main(string[] args) { int threadCount = 7;//задаём количество потоков string[] filelist = Directory.GetFiles(@"D:\logfiles", "*.txt"); m_threadResult = new System.Collections.Generic.List<StatLog>(threadCount); //и массив потоков System.Threading.Thread[] threads = new System.Threading.Thread[threadCount]; for (int i = 0; i < threadCount; ++i){ int id = i; m_threadResult.Add(new StatLog()); threads[i] = new System.Threading.Thread(() => threadFunc(id)); threads[i].Start(); } var statResult = m_threadResult[0]; for (int i = 1; i < m_threadResult.Count; ++i){ statResult.createStat(m_threadResult[i]); } Console.WriteLine("Создание файлов статистик"); StreamWriter sw = new StreamWriter(@"D:\userstat.txt"); //Пишем в файл foreach (var item in statResult.userstat){ sw.WriteLine("{0} {1}", item.Key, item.Value); Console.WriteLine("{0} {1}", item.Key, item.Value); } sw.Close(); StreamWriter sw1 = new StreamWriter(@"D:\adrestat.txt"); foreach (var item in statResult.adrestat){ sw1.WriteLine("{0} {1}", item.Key, item.Value); Console.WriteLine("{0} {1}", item.Key, item.Value); } sw1.Close(); StreamWriter sw2 = new StreamWriter(@"D:\trafikstat.txt"); foreach (var item in statResult.trafikstat) { sw2.WriteLine("{0} {1}", item.Key, item.Value); Console.WriteLine("{0} {1}", item.Key, item.Value); } sw2.Close(); Console.WriteLine("Файлы созданы"); Console.ReadKey(); } } }
Решение задачи: «Не считает файлы в статистику»
textual
Листинг программы
File.ReadAllText(text).Skip(skip)
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д