Good day to all. Help me figure it out, I wrote an application that records a binary file, but only writes 101 values, what could be the problem?

public void Cicle() { SectionHelper helper = new SectionHelper(); var Number_s = helper.AllocatedSection(8); var Year_s = helper.AllocatedSection(8); var Shift_s = helper.AllocatedSection(3); var Day_s = helper.AllocatedSection(5); var Month_s = helper.AllocatedSection(4); var R_s = helper.AllocatedSection(4); // пока не понял что за параметр. Int32 Line = 0; Int32 Line2 = 0; int Year2 = 0; int Day2 = 0; int Month2 = 0; int Shift2 = 0; int Rs2 = 0; int Number2 = 0; int NumberR = -1; string path = @"E:\DELETE\n.dat"; string path2 = @"E:\DELETE\nr.dat"; try { using (BinaryReader reader = new BinaryReader( File.Open( path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { using (BinaryReader reader2 = new BinaryReader( File.Open( path2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { while (reader.PeekChar() > -1) { Nr++; Line = reader.ReadInt32(); BitVector32 bv = new BitVector32(Line); int Number = bv[Number_s]; int Year = bv[Year_s]; int Shift = bv[Shift_s]; int Day = bv[Day_s]; int Month = bv[Month_s]; int Rs = bv[R_s]; if (reader2.PeekChar() > -1) { Line2 = reader2.ReadInt32(); BitVector32 bv2 = new BitVector32(Line2); Number2 = bv2[nr_s]; Year2 = bv2[y_s]; Shift2 = bv2[sm_s]; Day2 = bv2[d_s]; Month2 = bv2[m_s]; Rs2 = bv2[r_s]; } Console.WriteLine("Начальный параметр Line {0}", Line); if ((Line != Line2) & (Year > 14)) { using (BinaryWriter WriteNr = new BinaryWriter( File.Open( path2, FileMode.Append, FileAccess.Write, FileShare.ReadWrite) )) { WriteNr.Write(Line); //WriteNr.Close(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Запись в Nr Line:{0} И Line2:{1}", Line, Line2); Console.ResetColor(); } ReadSr _readSr = new ReadSr( Line2, Year2, Day2, Month2, Shift2, Nr2); if ((_readSr.NumberZ == NumberR) & (_readSr.flag)) { } else { ReadSr _readSr2 = new ReadSr( Line, Year, Day, Month, Shift, Nr); { if (_readSr2.flag) { SaveBinaryNumb save = new SaveBinaryNumb( _readSr2.NumberZ, _readSr2.TimeRelease, _readSr2.NumberRoll); } } } } } 

And the most interesting file in the dimension grows, and continues to grow until you close the program, and so alas it should not be, because there is a comparison of data from one file with another file, and if there are coincidences, then skip performing any actions. help me please

Closed due to the fact that off-topic participants Vadim Ovchinnikov , αλεχολυτ , user194374, aleksandr barakin , Kromster 9 Jan '17 at 8:22 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - αλεχολυτ, Community Spirit, aleksandr barakin, Kromster
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    Not exactly the topic, but it is hard to read and parse the code in which, instead of the human variable names, there are: Rs1, nz, ts, n, ds2, ms, sm, etc. You yourself are not sick to see it? - Bulson
  • one
    This is not aesthetics, but practicality. The code should be readable, and not look like encryption to the Center. - Bulson
  • one
    @ iluxa1810 Because I only study C #, and it just so happens that I don’t know many things, so I try to fill in my spaces and replenish my practice and experience, and you and this resource help me in this. For what you and All Thanks - Ethernets
  • 2
    I tried to copy your method to VS. I correctly understood that you also shoved using for writing inside the open using for readers? If yes, then this is game, to be honest. And why do you first create a bunch of variables, read values ​​from a file for them, and then create objects and copy the values ​​of variables into the attributes of these objects? It was necessary to immediately create instances of objects and immediately read their properties from the file values. Hard to be honest. You act incorrectly, do not try to rewrite this way. It is necessary to divide the task into parts and write again, looking into the old code. - Bulson
  • one
    @Ethernets, yes, you can overwrite everything from c ++ to C #, up to manual memory management, but this is not correct. You need to try to translate C ++ code to C # primitives, as well as try to refactor the source code, as it is possible, at the time of writing the code, this was acceptable, but many years have passed and technologies have changed and now all this can be rewritten in a more elegant style. . - iluxa1810

1 answer 1

Divide and rule the most ancient principle, which is suitable for programming. I sketched an approximate way to solve your problem with comments, suggestions and explanations. Naturally, he was not tested for errors in any way, consider it just a sketch of what should be. Coloring and painting it is your task.

 //методы принято называть с английскими глаголами вначале: Get,Set,Make,Load и т.д. public void MakeCycle() { //пути к файлам, адреса сайтов и проч. нужно делать //приватными константными полями класса //или параметрами метода, //но не локальными переменными метода string pathN = @"E:\DELETE\n.dat"; string pathNr = @"E:\DELETE\nr.dat"; //первый список List<ReadSr> listReadSr1 = GetListReadSr(pathN, new SectionHelper()); //проверяем, если получили пустой список, то прерываемся на этом if (!listReadSr1.Any()) return; //второй список List<ReadSr> listReadSr2 = GetListReadSr(pathNr, new SectionHelper()); //проверяем, если получили пустой список, то прерываемся на этом if (!listReadSr2.Any()) return; //теперь займемся сравнением и записью int count = CompareAndWriteReadSrLists(listReadSr1, listReadSr2, pathNr); } private List<ReadSr> GetListReadSr(string pathFile, SectionHelper helper) { //локальные переменные именуются со строчной буквы (чтобы отличать их от свойств и классов) var lengthNumber = helper.AllocatedSection(8); var lengthYear = helper.AllocatedSection(8); var lengthShift = helper.AllocatedSection(3); var lengthDay = helper.AllocatedSection(5); var lengthMonth = helper.AllocatedSection(4); var lengthRs = helper.AllocatedSection(4); //готовимся List<ReadSr> result = new List<ReadSr>(); ReadSr readSr = null; //читаем файл и создаем список объектов типа ReadSr try { using (BinaryReader reader = new BinaryReader( File.Open( pathFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { Int32 line = 0; BitVector32 bVector = null; while (reader.PeekChar() > -1) { line = reader.ReadInt32(); bVector = new BitVector32(line); //создаем новый экземпляр ReadSr //(я не знаю как в этом классе называются свойства, поэтому отсебятина ) readSr = new ReadSr() { Number = bVector[lengthNumber], Year = bVector[lengthYear], Shift = bVector[lengthShift], Day = bVector[lengthDay], Month = bVector[lengthDay], Rs = bVector[lengthRs] }; //добавляем в список новый экземпляр result.Add(readSr); } } } catch(Exception) { Debug.WriteLine("Ошибка чтения файла в методе GetReadSr()"); return new List<ReadSr>(); //ошибка, тогда пустой список } return result; } private int CompareAndWriteReadSrLists(List<ReadSr> sourceList, List<ReadSr> targetList, string pathFile) { //счетчик записанных элементов, который будем возвращать int result = 0; try { using (BinaryWriter writer = new BinaryWriter( File.Open( pathFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))) { for (int i = 0; i < sourceList.Count; i++) { //если экземпляры не равны и у источника год > 14 if (!ReadSrPropertiesCompare(sourceList[i], targetList[i]) && (sourceList[i].Year > 14)) { //пишем в файл writer.Write(sourceList[i]); //счетчик записанных элементов result++; } } } } catch() { Debug.WriteLine("Ошибка записи в файл в методе CompareAndWriteReadSrLists()"); } // return result; } private bool ReadSrPropertiesCompare(List<ReadSr> sourceElement, List<ReadSr> targetElement) { //здесь сравниваем все свойства у двух экземпляров //и если все свойства равны, то возвращаем true //а еще лучше в классе сделать override метода Equals() //и тогда этот метод бы не понадобился //а можно было бы сравнивать sourceElement.Equls(targetElement) }