internal static TObject Deserialize <TObject>(string filePath) where TObject : class { try { if (!FileFolderHelper.CreateFolderAndCheckFileExistance(filePath)) { throw new FileNotFoundException("File doesn't exist."); } var formatter = new BinaryFormatter(); using (var stream = new FileStream(filePath, FileMode.Open)) { return((TObject)formatter.Deserialize(stream)); } } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); throw new FileNotFoundException($"Failed to Deserialize Data From File {filePath}", ex); } catch (Exception ex) { Console.WriteLine(ex.Message); throw new Exception($"Failed to Deserialize Data From File {filePath}", ex); } }
/// <summary> /// Deserialize object from file and return it. If file is empty, return null. /// </summary> /// <typeparam name="TObject">type of object to deserialize</typeparam> /// <param name="filePath"></param> /// <returns>deserialized object</returns> internal static TObject Deserialize <TObject>(string filePath) where TObject : class { try { if (!FileFolderHelper.CreateFolderAndCheckFileExistance(filePath)) { throw new FileNotFoundException("File doesn't exist."); } var formatter = new BinaryFormatter(); using (var stream = new FileStream(filePath, FileMode.Open)) { // if file is empty, return null return(stream.Length == 0 ? null : (TObject)formatter.Deserialize(stream)); } } catch (FileNotFoundException ex) { throw new FileNotFoundException($"Failed to Deserialize Data From File {filePath}", ex); } catch (Exception ex) { throw new Exception($"Failed to Deserialize Data From File {filePath}", ex); } }