static void Main(string[] args) { //Helper.CheckDirectories(); var CurrentDomain = AppDomain.CurrentDomain.BaseDirectory; var GetDirectoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Console.WriteLine("AppDomain.CurrentDomain.BaseDirectory: {0}", CurrentDomain); Console.WriteLine("Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location): {0}", GetDirectoryName); ManualResetEvent manualResetEvent = new ManualResetEvent(true); manualResetEvent.WaitOne(); ConsoleWriteLine.WriteInConsole(null, null, null, "Project started", ConsoleColor.White); Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime; Process.GetCurrentProcess().PriorityBoostEnabled = true; Helper_WINWORD.Clear(); Helper_EXCEL.Clear(); ClearNormal(); ProgressOfUpdateAtStructAttribute Standart = (ProgressOfUpdateAtStructAttribute)ParentMethods.GetStandart().Clone_Full(); ValueForClient.DeserializeConfig(new TimeSpan(0, 5, 0)); // Deserialization data'es if (ValueForClient.ReadyStructure.ProgressOfUpdate is null ? true : ValueForClient.ReadyStructure.ProgressOfUpdate.List_ProgressOfUpdateAtStructAttribute.Count != 1) { Progress = Standart; ValueForClient.ReadyStructure.ProgressOfUpdate = new ProgressOfUpdate() { List_ProgressOfUpdateAtStructAttribute = new List <ProgressOfUpdateAtStructAttribute>() { Progress } }; }
public void Watcher_Turn(bool Turn) { if (PathFolder != null) { PathFolder.EnableRaisingEvents = Turn; ConsoleWriteLine.WriteInConsole(null, null, null, string.Format("\nClassName: {0}\nPathFolder: {1}\nTurn: {2}\nTimes: {3}\n", ClassName, PathFolder.Path, Turn, Times), ConsoleColor.White); } else { ConsoleWriteLine.WriteInConsole(null, null, null, string.Format("\nClassName: {0}\nPathFolder: {1}\nTurn: {2}\nTimes: {3}\n", ClassName, "NULL", Turn, Times), ConsoleColor.White); } }
/// <summary> /// Получить параметры, основываясь на их типе данных, записанного в string-формате /// </summary> /// <param name="ParametersSet"></param> /// <param name="dataSet"></param> /// <param name="NumbOfStartTable"></param> /// <returns></returns> private static Tuple <List <dynamic>, int> GetParametersByNameOfParameters(List <dynamic> ParametersSet, DataSet dataSet, int NumbOfStartTable) { List <dynamic> typeParameterReturns = new List <dynamic>(); List <dynamic> listDynamic = new List <dynamic>(); string ExceptionMessage = ""; foreach (dynamic parameter in ParametersSet) { if ((parameter).GetType() == (new List <string>().GetType())) { foreach (string s in parameter) { Tuple <dynamic, string> Item = GetInstenceFromThisNamespace(s); var someItem = Item.Item1; DataTable dt = dataSet.Tables[NumbOfStartTable]; var r = ConvertFrom(someItem, dt); listDynamic.Add(r); NumbOfStartTable++; } typeParameterReturns.Add(listDynamic); listDynamic = new List <dynamic>(); } else { var someItem = default(dynamic); Tuple <dynamic, string> Item = GetInstenceFromThisNamespace(parameter); someItem = Item.Item1; var r = default(dynamic); DataTable dt = dataSet.Tables[NumbOfStartTable]; r = ConvertFrom(someItem, dt); typeParameterReturns.Add(r); // Преобразованный экземпляр из dataSet NumbOfStartTable++; } } if (ExceptionMessage != "") { ConsoleWriteLine.WriteInConsole(nameof(GetParametersByNameOfParameters), "", "Failed", string.Format("{0}: {1}", MethodBase.GetCurrentMethod().Name, ExceptionMessage), default); } return(new Tuple <List <dynamic>, int>(typeParameterReturns, NumbOfStartTable)); }
private static readonly object lockObject = new object(); // очередь public void Watch(string MethodName, string ClassName, string dir, Tuple <bool, bool, bool, bool> Changed_Created_Deleted_Renamed, List <dynamic> Config) { if (!string.IsNullOrEmpty(dir)) { Times = 0; this.Config = Config; this.MethodName = MethodName; this.ClassName = ClassName; time = 5000; this.PathFolder = RunForFolders(dir, Changed_Created_Deleted_Renamed.Item1, Changed_Created_Deleted_Renamed.Item2, Changed_Created_Deleted_Renamed.Item3, Changed_Created_Deleted_Renamed.Item4); ConsoleWriteLine.WriteInConsole(this.MethodName, "Watch", "Start", "", ConsoleColor.White); } }
private FileSystemWatcher RunForFolders(string Path, bool Changed, bool Created, bool Deleted, bool Renamed) { // Create a new FileSystemWatcher and set its properties. FileSystemWatcher watcher = new FileSystemWatcher(); try { watcher.Path = Path; } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(null, null, "Failed", ex.Message.ToString(), ConsoleColor.Red); return(null); } /* Watch for changes in LastAccess and LastWrite times, and * the renaming of files or directories. */ watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.Attributes; // Add event handlers. if (Changed) { watcher.Changed += new FileSystemEventHandler(Watcher_Process); } if (Created) { watcher.Created += new FileSystemEventHandler(Watcher_Process); } if (Deleted) { watcher.Deleted += new FileSystemEventHandler(Watcher_Process); } if (Renamed) { watcher.Renamed += new RenamedEventHandler(Watcher_Process); } return(watcher); }
private static List <T> ToListof <T>(this DataTable dt) { try { const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; var columnNames = dt.Columns.Cast <DataColumn>() .Select(c => c.ColumnName) ; var objectProperties = typeof(T).GetProperties(flags); var targetList = dt.AsEnumerable().Select(dataRow => { T instanceOfT; if (typeof(T) == typeof(string)) { instanceOfT = (T)Activator.CreateInstance("".GetType(), "".ToCharArray()); } else { instanceOfT = (T)Activator.CreateInstance <T>(); } try { foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value)) { properties.SetValue(instanceOfT, dataRow[properties.Name], null); } } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(nameof(ToListof), "", "Failed", ex.ToString(), default); } return(instanceOfT); }).ToList(); return(targetList); } catch { return(dt.ToListof <T>()); } }
private static void StartListening() { Priority = Thread.CurrentThread.Priority; try { if (!Helper.IsLocked(StartListening_LockObject)) { lock (StartListening_LockObject) using (listener = new Socket(localEndPoint.AddressFamily, // Bind the socket to the local endpoint and listen for incoming connections. SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = (int)Math.Round(TimeSpan.FromMinutes(2).TotalMilliseconds), SendTimeout = (int)Math.Round(TimeSpan.FromMinutes(2).TotalMilliseconds), }) // Create a TCP/IP socket. { listener.Bind(localEndPoint); listener.Listen(5); while (true) { AllDone.Reset(); // Set the event to nonsignaled state. ConsoleWriteLine.WriteInConsole(null, null, null, "\nWaiting for a new connection...", ConsoleColor.White); // Start an asynchronous socket to listen for connections. listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); AllDone.WaitOne(); // Wait until a connection is made before continuing. } } } } catch (ThreadAbortException ex) { StartListening(); } catch (SocketException ex) { StartListening(); } catch (Exception ex) { StartListening(); } }
/// <summary> /// Запуск прослушки сокета /// </summary> /// <param name="ClassName">Класс для взаимодействия запросов клиента</param> /// <param name="Port"></param> /// <param name="Parent"></param> public static void StartListening(string ClassName, int Port) { var Priority = Thread.CurrentThread.Priority; foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces()) { ConsoleWriteLine.WriteInConsole(null, null, null, "Name: " + netInterface.Name, ConsoleColor.White); ConsoleWriteLine.WriteInConsole(null, null, null, "Description: " + netInterface.Description, ConsoleColor.White); ConsoleWriteLine.WriteInConsole(null, null, null, "Addresses: ", ConsoleColor.White); IPInterfaceProperties ipProps = netInterface.GetIPProperties(); foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses) { ConsoleWriteLine.WriteInConsole(null, null, null, " " + addr.Address.ToString(), ConsoleColor.White); } } ConnectFromServer.ClassName = ClassName; localEndPoint = new IPEndPoint(IPAddress.Any, Port); ConsoleWriteLine.WriteInConsole(null, null, null, string.Format("Local IP: {0}", Helper.GetLocalIPv4(NetworkInterfaceType.Ethernet)), ConsoleColor.White); StartListening(); }
public static T DeserializeState_ToNetWork <T>(byte[] bytes, out string Exception, out TimeSpan TimeSpend) // Десериализация { DateTime Start = DateTime.Now; Exception = ""; T Returned = default; using (var ms = new MemoryStream(bytes)) using (var deflateStream = new DeflateStream(ms, CompressionMode.Decompress, true)) try { Returned = (T) new BinaryFormatter().Deserialize(deflateStream); } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(nameof(DeserializeState_ToNetWork), "", "Failed", ex.Message.ToString(), default); Exception = ex.Message.ToString(); } bytes = null; TimeSpend = DateTime.Now - Start; return(Returned); }
public static byte[] SerializeState_ToNetWork <T>(T obj, out string Exception, out TimeSpan TimeSpend) // Сериализация { DateTime Start = DateTime.Now; Exception = ""; byte[] bytes = default; try { using (MemoryStream stream = new MemoryStream()) { using (var deflateStream = new DeflateStream(stream, CompressionMode.Compress, true)) try { new BinaryFormatter().Serialize(deflateStream, obj); } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(nameof(SerializeState_ToNetWork), "", "Failed", ex.Message.ToString(), default); Exception = ex.Message.ToString(); } stream.Position = 0; bytes = stream.GetBuffer(); } } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(nameof(SerializeState_ToNetWork), "", "Failed", ex.Message.ToString(), default); Exception = ex.Message.ToString(); } TimeSpend = DateTime.Now - Start; return(bytes); }
/// <summary> /// Конструктор для отправки данных /// </summary> /// <param name="handler"></param> /// <param name="SomeBytes"></param> public ProtocolSendRecieve(Socket handler, byte[] SomeBytes) { StartConnection = DateTime.Now; if (SomeBytes.Count() == 0) { throw new Exception("SomeBytes.Count == 0"); } if (handler is null ? false : handler.Connected) { StructSetData = new Dictionary <string, Tuple <bool, string, TimeSpan> >() { { string.Format("Stage: '{0}'", "Start"), null }, { string.Format("Stage: '{0}'", "Send bytes length"), null }, { string.Format("Stage: '{0}'", "Get message about bytes length"), null }, { string.Format("Stage: '{0}'", "Send bytes"), null }, { string.Format("Stage: '{0}'", "Done"), null }, { string.Format("Stage: '{0}'", string.Format("Set '{0}'", MessageToConnect)), null }, { string.Format("Stage: '{0}'", string.Format("Exception: '{0}'", ExceptionMessage_NotRespond)), null }, }; ExceptionMessage = ""; NewIvents(); Thread Thread = new Thread(() => { if (Thread.CurrentThread.Name is null) { Thread.CurrentThread.Name = nameof(ProtocolSendRecieve) + "_Send"; } try { StructSetData[string.Format("Stage: '{0}'", "Start")] = new Tuple <bool, string, TimeSpan>(true, string.Format("Send start. Bytes: {0}", SomeBytes.Length), DateTime.Now - StartConnection); StatusReceieve = new ManualResetEvent(false); Send(new StateObject(handler, SomeBytes)); StatusReceieve.WaitOne(WaitTime); StructSetData[string.Format("Stage: '{0}'", "Done")] = new Tuple <bool, string, TimeSpan>(true, "Send done", DateTime.Now - StartConnection); } catch (ThreadAbortException ex) { ExceptionMessage = ex.Message.ToString(); ConsoleWriteLine.WriteInConsole(nameof(ProtocolSendRecieve), "Send", "Failed", ExceptionMessage, default); } catch (ObjectDisposedException ex) { ExceptionMessage = ex.Message.ToString(); ConsoleWriteLine.WriteInConsole(nameof(ProtocolSendRecieve), "Send", "Failed", ExceptionMessage, default); } catch (SocketException ex) { ExceptionMessage = ex.Message.ToString(); ConsoleWriteLine.WriteInConsole(nameof(ProtocolSendRecieve), "Send", "Failed", ExceptionMessage, default); } catch (RuntimeWrappedException ex) { ExceptionMessage = ex.Message.ToString(); ConsoleWriteLine.WriteInConsole(nameof(ProtocolSendRecieve), "Send", "Failed", ExceptionMessage, default); } catch (Exception ex) { ExceptionMessage = ex.Message.ToString(); ConsoleWriteLine.WriteInConsole(nameof(ProtocolSendRecieve), "Send", "Failed", ExceptionMessage, default); } catch { ExceptionMessage = MethodBase.GetCurrentMethod().Name + " catch"; ConsoleWriteLine.WriteInConsole(nameof(ProtocolSendRecieve), "Send", "Failed", ExceptionMessage, default); } }); try { Thread.Priority = ThreadPriority.Highest; Thread.Start(); Thread.Join(WaitTime); } catch (ThreadStateException ex) { ExceptionMessage = ex.ToString(); } catch (ThreadStartException ex) { ExceptionMessage = ex.ToString(); } catch (ThreadAbortException ex) { ExceptionMessage = ex.ToString(); } catch (NullReferenceException ex) { ExceptionMessage = ex.ToString(); } if (Thread is null ? false : Thread.IsAlive) { try { ExceptionMessage = "Time is out"; Thread.Abort(); Thread = null; } catch { } } } }
/// <summary> /// Чтение инструкции /// </summary> /// <param name="dataSetWithInstruction"></param> /// <returns></returns> public static Tuple <List <dynamic>, List <dynamic>, string> ReadInstructions(DataSet dataSetWithInstruction) { DataTable dt = new DataTable(); try { dt = dataSetWithInstruction.Tables[dataSetWithInstruction.Tables.Count - 1]; } catch (Exception ex) { string Exception = ex.Message.ToString(); ConsoleWriteLine.WriteInConsole(null, null, "Failed", Exception, ConsoleColor.Red); return(new Tuple <List <dynamic>, List <dynamic>, string>(new List <dynamic>(), new List <dynamic>(), "")); } string[] datatableStrings = (dt.Rows[0][0].ToString()).Split(';'); List <dynamic> ItemsSet = new List <dynamic>(); List <dynamic> ItemsReturn = new List <dynamic>(); bool isReturnItem = false; int NumbItemReturns = 0; string NameOfCallMethod = ""; bool isNameOfCallMethod = true; List <string> dynamics = new List <string>(); bool isListDynamic = false; foreach (string parameter in datatableStrings) { if (isNameOfCallMethod) { NameOfCallMethod = parameter; isNameOfCallMethod = false; } else { if (parameter == "<Start: List <dynamic>>") { isListDynamic = true; } else if (parameter == "<End: List <dynamic>>") { isListDynamic = false; if (isReturnItem) // В первую очередь считываются поступающие параметры { ItemsReturn.Add(dynamics); // Параметры на возврат } else { ItemsSet.Add(dynamics); // Поступающие параметры } dynamics = new List <string>(); } else if (isListDynamic) { dynamics.Add(parameter); } else if (Int32.TryParse(parameter, out NumbItemReturns)) { isReturnItem = true; } else { if (isReturnItem) // В первую очередь считываются поступающие параметры { ItemsReturn.Add(parameter); // Параметры на возврат } else { ItemsSet.Add(parameter); // Поступающие параметры } } } } return(new Tuple <List <dynamic>, List <dynamic>, string>(ItemsSet, ItemsReturn, NameOfCallMethod)); }
public void WriteInConsole(string Module, string Process, string Status, string Comment, ConsoleColor consoleColor) { ConsoleWriteLine.WriteInConsole(Module, Process, Status, Comment, consoleColor); }
/// <summary> /// Прослойка/адаптер. Призван конвертировать входящий запрос, обработать на сервере и отправить обратный ответ /// </summary> /// <param name="bytes"></param> /// <param name="MYIpClient"></param> /// <param name="ClassName"></param> /// <param name="Parent"></param> /// <returns></returns> public static Tuple <byte[], string> CommonProcess(byte[] bytes, string MYIpClient, string ClassName) { byte[] Bytes_FromServerToClient = default; { DataToSerialize Data_FromClient = default; { DateTime TimeDeSerialize_Start = DateTime.Now; DataToBinary.Convert(bytes, out Data_FromClient, out string Exception); if (!string.IsNullOrEmpty(Exception)) { } TimeSpan TimeDeSerialize = DateTime.Now - TimeDeSerialize_Start; if (TimeDeSerialize > TimeSpan.FromSeconds(5)) { } } if (!(Data_FromClient is null)) { Tuple <List <dynamic>, string, List <dynamic> > ParametersFromDataSet = Converter.GetParametersFromDataSet(Data_FromClient.dataset); List <dynamic> SetParameters = ParametersFromDataSet.Item1; // Поступающие параметры if (SetParameters.Count > 0 ? SetParameters[0] is StructureValueForClient : false) { SetParameters[0] = Data_FromClient.ReadyStructure; } string NameOfCallMethod = ParametersFromDataSet.Item2; // Имя метода обработчика if (string.IsNullOrEmpty(NameOfCallMethod)) { throw new Exception("Calling method not found"); // It's a exception } else { List <dynamic> ReturnParameters = ParametersFromDataSet.Item3; // Возвращаемые параметры string comment = string.Format("({0}) to access [ {1} ]", MYIpClient, NameOfCallMethod); ConsoleWriteLine.WriteInConsole("Network", "Listener", "In Process", comment, ConsoleColor.White); List <dynamic> ReturnItems_FromServer = null; string Instruction_FromServer = null; ReturnItems_FromServer = ProcessThis(SetParameters, ReturnParameters, NameOfCallMethod, ClassName); ReturnItems_FromServer = ReturnItems_FromServer is null ? null : ReturnItems_FromServer.Select(x => { return(x is null ? "" : x); }).ToList(); Instruction_FromServer = Instructions.CreateInstructions(ReturnItems_FromServer, new List <dynamic>(), ""); // Собрали инструкцию для клиента DataSet Date_FromServer = Converter.ConvertFrom(ReturnItems_FromServer, new List <dynamic>(), Instruction_FromServer); if (ReturnItems_FromServer.Count > 0) { DateTime TimeRecieve_Start = DateTime.Now; dynamic Data_FromServerToClient = ReturnItems_FromServer[0]; if (Data_FromServerToClient is StructureValueForClient) // GetParamatersForClientReady { DateTime LastTime = default; string Key = ""; { // Check Time and properties Dictionary <string, MainParentClass> props = Helper.GetProperties <MainParentClass, StructureValueForClient>((StructureValueForClient)Data_FromServerToClient); foreach (var From in props) { string Name = From.Key; if (Name != "Log_File") { Key += Name; var ReadyStructure_Type = ((StructureValueForClient)Data_FromServerToClient).GetType(); if (!(ReadyStructure_Type is null)) { var To_Property = ReadyStructure_Type.GetField("updateTime_Module_" + Name); if (!(To_Property is null)) { DateTime To_Value = (DateTime)To_Property.GetValue((StructureValueForClient)Data_FromServerToClient); LastTime += To_Value.TimeOfDay; // сумма проверит включит все элементы } } } } } lock (AlreadySerialized) { var Finded = AlreadySerialized.FirstOrDefault(x => x.Key.Equals(Key) || x.Key == Key); if (Finded.Value is null ? false : Finded.Value.Item2 != LastTime) // remove old serialized properties { AlreadySerialized.Remove(Finded.Key); Finded = default; } if (!(Finded.Key is null)) { Bytes_FromServerToClient = Finded.Value.Item1; // return already serialized } else { DateTime TimeSerialize_Start = DateTime.Now; DataToBinary.Convert(Date_FromServer, (StructureValueForClient)Data_FromServerToClient, out Bytes_FromServerToClient, out string Exception);// Конвертнули датасет в байты TimeSpan TimeSerialize = DateTime.Now - TimeSerialize_Start; if (!string.IsNullOrEmpty(Exception)) { } if (TimeSerialize > TimeSpan.FromSeconds(5)) { } { DateTime DeserializeStart = DateTime.Now; DataToBinary.Convert(Bytes_FromServerToClient, out DataToSerialize ReturnDataSet, out string Ex); // Десериализация TimeSpan Deserialize = DateTime.Now - DeserializeStart; if (!string.IsNullOrEmpty(Ex)) { DataToBinary.Convert(Date_FromServer, (StructureValueForClient)Data_FromServerToClient, out Bytes_FromServerToClient, out string Exceptionn);// Конвертнули датасет в байты } } if (!string.IsNullOrEmpty(Key)) { if (AlreadySerialized.FirstOrDefault(x => x.Key == Key).Key is null) { AlreadySerialized.Add(Key, new Tuple <byte[], DateTime>(Bytes_FromServerToClient, LastTime)); // serialize new properties } } } } }
public static T DeSerializeObject_ToFile <T>(out TimeSpan SpendOnIt, string FullPath) // Chosen path { SpendOnIt = default(TimeSpan); string fileName = FullPath + (Format); string fileName_Temp = FullPath + "_Temp" + (Format); if (string.IsNullOrEmpty(fileName) ? true : !File.Exists(fileName)) { ConsoleWriteLine.WriteInConsole(nameof(DeSerializeObject_ToFile), "", "Failed", "File not exist", ConsoleColor.Red); return(Converter.CreateInstance <T>()); } T objectOut = Converter.CreateInstance <T>(); TimeSpan timeStart = DateTime.Now.TimeOfDay; try { ConsoleWriteLine.WriteInConsole(string.Format("DeSerializeObject: {0}", Path.GetFileName(fileName)), "", "Started", "At: " + (DateTime.Now.TimeOfDay), ConsoleColor.DarkMagenta); try { using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate)) objectOut = (T) new BinaryFormatter().Deserialize(fs); } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(nameof(DeSerializeObject_ToFile), "", "Failed", ex.Message.ToString(), default); if (File.Exists(fileName)) { File.Delete(fileName); } } ConsoleWriteLine.WriteInConsole(string.Format("DeSerializeObject: {0}", Path.GetFileName(fileName)), "", "Done", "Time on it: " + (SpendOnIt = (DateTime.Now.TimeOfDay - timeStart)), ConsoleColor.DarkMagenta); } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(nameof(DeSerializeObject_ToFile), "", "Failed", ex.Message.ToString(), default); if (File.Exists(fileName)) { File.Delete(fileName); } ConsoleWriteLine.WriteInConsole(string.Format("DeSerializeObject: {0}", Path.GetFileName(fileName)), "", "Failed", "Time on it: " + (SpendOnIt = (DateTime.Now.TimeOfDay - timeStart)) + "; Exception: " + ex.Message.ToString(), ConsoleColor.DarkMagenta); if (File.Exists(fileName_Temp)) { try { using (FileStream fs = new FileStream(fileName_Temp, FileMode.OpenOrCreate)) objectOut = (T) new BinaryFormatter().Deserialize(fs); } catch (Exception exx) { ConsoleWriteLine.WriteInConsole(nameof(DeSerializeObject_ToFile), "", "Failed", ex.Message.ToString(), default); if (File.Exists(fileName_Temp)) { File.Delete(fileName_Temp); } } } } FullPath = null; return(objectOut); }
public static void SerializeObject_ToFile <T>(string FullPath, T serializableObject, out TimeSpan SpendOnIt) // Chosen path { SpendOnIt = default; string fileName = FullPath + (Format); string fileName_Temp = FullPath + "_Temp" + (Format); if (!IsDeSerializeObject) { if (serializableObject == null) { return; } lock (serializableObject) { TimeSpan timeStart = DateTime.Now.TimeOfDay; try { if (!Directory.Exists(Path.GetDirectoryName(fileName))) { Directory.CreateDirectory(Path.GetDirectoryName(fileName)); } using (FileStream fs = new FileStream(fileName_Temp, FileMode.OpenOrCreate)) new BinaryFormatter().Serialize(fs, serializableObject); ConsoleWriteLine.WriteInConsole(string.Format("SerializeObject: {0}", Path.GetFileName(fileName)), "", "Done", "Time on it: " + (SpendOnIt = (DateTime.Now.TimeOfDay - timeStart)), ConsoleColor.DarkMagenta); } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(string.Format("SerializeObject: {0}", Path.GetFileName(fileName)), "", "Failed", "Time on it: " + (SpendOnIt = (DateTime.Now.TimeOfDay - timeStart)) + "; Exception: " + ex.Message.ToString(), ConsoleColor.DarkMagenta); if (File.Exists(fileName)) { File.Delete(fileName); } } try { if (File.Exists(fileName)) { File.Delete(fileName); } if (!File.Exists(fileName)) { File.Copy(fileName_Temp, fileName); } } catch (Exception ex) { ConsoleWriteLine.WriteInConsole(nameof(SerializeObject_ToFile), "", "Failed", ex.Message.ToString(), default); if (File.Exists(fileName_Temp)) { File.Delete(fileName_Temp); } if (File.Exists(fileName)) { File.Delete(fileName); } } } FullPath = null; } }