Вывод данных в файл через сервер - C#
Формулировка задачи:
Народ, подскажите пожалуйста, почему мои данные выводятся в файл в одну строку, а не происходит переноса на новую строку, к тому же пробел исчез..как выглядит сейчас:
0: 28.06.2016 22:42:511: 28.06.2016 22:42:522: 28.06.2016 22:42:533: 28.06.2016 22:42:544: 28.06.2016 22:42:55
А должно выводиться так:
0: 28.06.2016 22:42:51
1: 28.06.2016 22:42:52
2: 28.06.2016 22:42:53
3: 28.06.2016 22:42:54
4: 28.06.2016 22:42:55
Суть в том, что от клиента приходят эти данные на сервак, в переменную message..сервер их записывает в файл, затем через минуту происходит перезапись..
Вот код класса Program.
Заранее спасибо!
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)
}
}
}
И код класса 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();
}
}
}
И еще, очистка происходит не через минуту, а секунд через 5..почему так? помогите плиз
Решение задачи: «Вывод данных в файл через сервер»
textual
Листинг программы
string message = builder.ToString() + "\n";