People, please tell me why my data is displayed in a file in one line, and there is no transfer to a new line, besides the space has disappeared .. as it looks now:

0: 28.06.2016 22: 42: 511: 28.06.2016 22: 42: 522: 06.28.2016 22: 42: 533: 06.28.2016 22: 42: 544: 28.06.2016 22:42:55

A should be displayed as:

0: 06/28/2016 10:42:51 PM

1: 06/28/2016 10:42:52 PM

2/28/2016 10:42:53

03/28/2016 10:42:54 PM

04/28/2016 10:42:55 PM

The bottom line is that this data comes from the client to the server, writes it to the variable message..server in a file, then overwrites after a minute ..

class Program { const int port = 8888; static TcpListener listener; static void Main(string[] args) { try { var aTimer = new System.Timers.Timer(); aTimer.Interval = 10000; aTimer.AutoReset = true; aTimer.Start(); listener = new TcpListener(IPAddress.Parse("127.0.0.1"), port); listener.Start(); aTimer.Elapsed += OnTimedEvent; Console.WriteLine("Ожидание подключений..."); while (true) { TcpClient client = listener.AcceptTcpClient(); ClientObject clientObject = new ClientObject(client); // создаем новый поток для обслуживания нового клиента Thread clientThread = new Thread(new ThreadStart(clientObject.Process)); clientThread.Start(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (listener != null) listener.Stop(); } } private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) { // Check file access //delete file's old content var file = new FileInfo("log.txt"); try { //stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None); string[] lines = File.ReadAllLines(@"log.txt"); StringBuilder newLines = new StringBuilder(); foreach (var line in lines) { var date = Convert.ToDateTime(line.Substring(line.IndexOf(' ') + 1)); var currentTime = DateTime.Now; if(date>=currentTime.AddMinutes(-1)) { newLines.Append(line + "\n"); } } Console.WriteLine("Cleaning..."); using (FileStream fstream = new FileStream("log.txt", FileMode.Create)) { // запись массива байтов в файл byte[] array = Encoding.Default.GetBytes(newLines.ToString()); fstream.Write(array, 0, array.Length); } } catch (IOException) { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) } } } 

And the class code ClientObject

 public class ClientObject { public TcpClient client; public ClientObject(TcpClient tcpClient) { client = tcpClient; } public void Process() { NetworkStream stream = null; try { stream = client.GetStream(); byte[] data = new byte[64]; // буфер для получаемых данных while (true) { // получаем сообщение StringBuilder builder = new StringBuilder(); int bytes = 0; do { bytes = stream.Read(data, 0, data.Length); builder.Append(Encoding.Unicode.GetString(data, 0, bytes)); } while (stream.DataAvailable); string message = builder.ToString() + "\n"; Console.WriteLine("Записываю в log {0}", message); try { using (FileStream fstream = new FileStream("log.txt", FileMode.Append)) { // преобразуем строку в байты byte[] array = Encoding.Default.GetBytes(message); // запись массива байтов в файл fstream.Write(array, 0, array.Length); //Console.WriteLine("Текст записан в файл"); } } catch(Exception ex) { // ERROR MESSAGE TO CLIENT //message = ex.Message; //data = Encoding.Unicode.GetBytes(message); //stream.Write(data, 0, data.Length); } // отправляем обратно сообщение в верхнем регистре //message = message.Substring(message.IndexOf(':') + 1).Trim().ToUpper(); //data = Encoding.Unicode.GetBytes(message); //stream.Write(data, 0, data.Length); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (stream != null) stream.Close(); if (client != null) client.Close(); } } } 
  • 2
    The problem about the correct record is solved! It was necessary to add \ r \ n. - ZeRR
  • Please tell me about the re-recording time, I need it in a minute, but I have 5-6 overwrites in seconds, although I tried to calculate the time difference .. - ZeRR
  • one
    The easiest way to start a class in which your received data and the time of the last entry will be stored and in a loop, or else periodically check the current time. Yes, and your code is 10,000 milliseconds, in translation - it is 10 seconds. - Luchunpen

1 answer 1

Add Environment.NewLine (or \r\n ). Yes, and since you have already found the answer to the question, then close it! Hanging in the unanswered lists, came here just because of this.