I'm using binaryFormatter to encrypt data but i wanna save it without encryption.
so next time i just cast it .
this is the code that i'm using.
//Creat a binaryFormatter
BinaryFormatter formatter = new BinaryFormatter();
//Direction, Filename and Extention
string path = Application.persistentDataPath + "/enem.sav";
//Creat the File (Blank)
FileStream stream = new FileStream(path, FileMode.Create);
//Get the Data
EnemData data = new EnemData();
//Enter the Data and Encrypt it
formatter.Serialize(stream, data);
stream.Close();
You can use JsonUtility.ToJson to convert your object's data into JSON format.
public class PlayerState : MonoBehaviour
{
public string playerName;
public int lives;
public float health;
public string SaveToString()
{
return JsonUtility.ToJson(this);
}
// Given:
// playerName = "Dr Charles"
// lives = 3
// health = 0.8f
// SaveToString returns:
// {"playerName":"Dr Charles","lives":3,"health":0.8}
}
Here you can find how to read and write a string to and from a file.
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
// Open the file to read from.
string readText = File.ReadAllText(path);
To load the data simply use JsonUtility.FromJson or JsonUtility.FromJsonOverwrite.
Example:
public class PlayerState : MonoBehaviour
{
public string playerName;
public int lives;
public float health;
public string path = "your file path";
public string SaveToString()
{
File.WriteAllText(path, JsonUtility.ToJson(this));
}
public static PlayerState Load(string path)
{
return JsonUtility.FromJson<PlayerState>(File.ReadAllText(path));
}
}
Not sure about what you need. If you just want to serialize (turn your class into a binary representation and save to a file) and then get it back this should work for your:
//Create a binaryFormatter
BinaryFormatter formatter = new BinaryFormatter();
//Direction, Filename and Extention
string path = Application.persistentDataPath + "/enem.sav";
//Creat the File (Blank)
Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
//Get the Data
EnemData data = new EnemData { Id = 123, SomeBool = true, Name = "Enem" };
//Enter the Data and Encrypt it
formatter.Serialize(stream, data);
stream.Close();
//Restore it
Stream stream2 = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
EnemData restoredClass = (EnemData)formatter.Deserialize(stream2);
stream.Close();
But remember that you have to mark your class as serializable:
[Serializable]
public class EnemData
{
public int Id { get; set; }
public bool SomeBool { get; set; }
public string Name { get; set; }
}
Related
I'm currently trying to set a "firstRun" boolean to run a piece of code only when the app is started for the first time.
GameData.cs
[System.Serializable]
public class GameData
{
public static string saveFileName = "Pixel.pixel";
public double money;
public bool firstRun;
public GameData()
{
money = GameController.Instance.CurrentCash;
}
}
SaveSystem.cs
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem
{
public static void SaveData()
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/" + GameData.saveFileName;
FileStream stream = new FileStream(path, FileMode.Create);
GameData data = new GameData();
formatter.Serialize(stream, data);
stream.Close();
}
public static GameData LoadData()
{
string path = Application.persistentDataPath + "/" + GameData.saveFileName;
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
GameData data = formatter.Deserialize(stream) as GameData;
stream.Close();
return data;
}
else
{
return null;
}
}
}
GameController.cs part
public void Start()
{
Setup(START_CASH);
/*AddCash(START_CASH);*/
}
private void Setup(double value)
{
GameData data = SaveSystem.LoadData();
if (!data.firstRun)
{
CurrentCash += value;
SaveSystem.SaveData();
}
else
{
CurrentCash = data.money;
SaveSystem.SaveData();
}
UI.CashDisplay.text = ShortScaleString.parseDouble(CurrentCash, 1, 1000, scientificFormat);
}
My problem is that I need to check if "data.firstRun" is false/doesn't exist to run a setup part but I literally don't know how to achieve this
You should just return a new 'GameData', with your prefered value (true or false):
public static GameData LoadData()
{
string path = Application.persistentDataPath + "/" + GameData.saveFileName;
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
GameData data = formatter.Deserialize(stream) as GameData;
stream.Close();
return data;
}
else
{
return new GameData { firstRun = true };
}
}
So, I'm currently using C# in unity to create a save file in any operational system
using the "Application.persistentDataPath" command.
on windows 10 it's supposed to create this file in
C:\Users\User\AppData\LocalLow
thing is, it isn't creating the file.
while the application is open, the data is saved and stored, when I load, everything saved comes up
but when the application is closed and open again, the previous saved data simply doesn't exists
I'm just trying to make it create a file, and save data in it
I have tried several videos, several personal courses and I followed each and every single one of them
so far, the save function worked, but as described, no save file is created
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using System.Collections.Generic;
public static class SaveSystem
{
public static BeerPiratePS beerpirateps { get; private set; }
public static BeerPS beerps { get; private set; }
public static BeerPubPS beerpubps { get; private set; }
public static FactoryPS factoryps { get; private set; }
public static GlobalBeer globalbeer { get; private set; }
public static BeerChemistsPS beerchem { get; private set; }
public static MainButtonClick mainbuttonclick { get; private set; }
public static void SavePlayer ()
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = File.Create(Application.persistentDataPath + "/beerplayer.ber");
Debug.Log("BEER SAVED AAAAAAAAAAAAAAAAAAA");
PlayerData dataPub = new PlayerData(beerpubps);
PlayerData dataDwarves = new PlayerData(factoryps);
PlayerData dataPirates = new PlayerData(beerpirateps);
PlayerData dataBrew = new PlayerData(beerps);
PlayerData dataGlobal = new PlayerData(globalbeer);
PlayerData dataChemist = new PlayerData(beerchem);
PlayerData dataClick = new PlayerData(mainbuttonclick);
formatter.Serialize(stream, dataPub);
formatter.Serialize(stream, dataPirates);
formatter.Serialize(stream, dataDwarves);
formatter.Serialize(stream, dataBrew);
formatter.Serialize(stream, dataGlobal);
formatter.Serialize(stream, dataClick);
formatter.Serialize(stream, dataChemist);
stream.Close();
}
public static PlayerData LoadPlayer()
{
string path = Application.persistentDataPath + "/beerplayer.ber";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = File.Open(Application.persistentDataPath + "/beerplayer.ber", FileMode.Open);
Debug.Log("BEER FOUND AAAAAAAAAAAAAAAAAAAAAAAAAAA");
PlayerData dataPub = (PlayerData)formatter.Deserialize(stream) as PlayerData;
PlayerData dataPirates = (PlayerData)formatter.Deserialize(stream) as PlayerData;
PlayerData dataDwarves = (PlayerData)formatter.Deserialize(stream) as PlayerData;
PlayerData dataBrew = (PlayerData)formatter.Deserialize(stream) as PlayerData;
PlayerData dataGlobal = (PlayerData)formatter.Deserialize(stream) as PlayerData;
PlayerData dataClick = (PlayerData)formatter.Deserialize(stream) as PlayerData;
PlayerData dataChemist = (PlayerData)formatter.Deserialize(stream) as PlayerData;
stream.Close();
return dataChemist;
}
else
{
Debug.LogError("NO BEER FOUND AAAAAAAAAAAAAAAAAAAAA" + path);
return null;
}
}
}
surprisingly, the logError "NO BEER FOUND AAAAAAAAAAAAAAAAAA" hasn't appeared once
I know this should be simple but I am naive in c#. I have the following object to generate as csv. and I am successfully able to generate a csv string using the method here
[Serializable]
public class UserSession
{
public string UserName { get; set; }
public string UserGuid { get; set; }
public string MachineGuid { get; set; }
public Guid SessionGuid { get; set; }
public DateTime LoginTime { get; set; }
public DateTime? LogOffTime { get; set; }
public TimeSpan? DesktopReady { get; set; }
public bool IsReadable { get; set; }
public int SessionId { get; set; }
}
Now I want to save this file in a specified path (for eg :
c://csvfolder/{myFilename}.csv
Can anyone suggest a method to write this csv file to 'myFilename.csv' and save it in c://csvfolder in c#??
That should be pretty simple. It looks like you have a generic class that can serialize your object into a string buffer.
All there's left is to take the string containing the CSV data and write it to a file. Fortunately that's quite trivial in C#:
string path = #"c:\csvfolder\myFilename.csv";
// assuming there's a UserSession object called userSessionObject..
string csvData = ToCsv<UserSession>(",", new [] {userSessionObject});
File.WriteAllText(path, csvData);
Try the following code, for saving the CSV File (Includes the creation of CSV)
string path = "c://csvfolder";
string fileName = "FileName.csv";
StreamWriter SW = new StreamWriter(path, false);
SW.Write( /*Can create the comma sperated items*/);
/*Create y our CSV file data here*/
fs = File.Open(path, FileMode.Open);
int BUFFER_SIZE = Convert.ToInt32(fs.Length);
int nBytesRead = 0;
Byte[] Buffer = new Byte[BUFFER_SIZE];
nBytesRead = fs.Read(Buffer, 0, BUFFER_SIZE);
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(Buffer);
Response.Flush();
Response.End();
I want to write an object (using XmlDictionaryWriter) to memory stream and read it back. I have the following code. When I read back the object from Memory Stream it crashes. The crash message is: Additional information: There was an error deserializing the object of type Obj_4_1_Perform_IO_Operations.FullName. The data at the root level is invalid. Line 1, position 1.
[DataContract]
public class FullName
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
FullName fn = new FullName();
fn.LastName = "John";
fn.LastName = "Doe";
MemoryStream ms = Process(fn);
Console.WriteLine("Read Back");
ms.Position = 0;
DataContractSerializer serializer = new DataContractSerializer(typeof(FullName));
FullName fn2 = (FullName)serializer.ReadObject(ms); //<--- crash here
Console.WriteLine("Deserialized record: {0} {1}", fn2.FirstName, fn2.LastName);
}
public static MemoryStream Process(FullName name)
{
var ms = new MemoryStream();
var binary = XmlDictionaryWriter.CreateBinaryWriter(ms);
var ser = new DataContractSerializer(typeof(FullName));
ser.WriteObject(binary, name);
binary.Flush();
Console.WriteLine("MemoryStream is {0} bytes long", ms.Length);
return ms;
}
}
Is there a way to save a list to disk generically? I tried data contract serializer, but it always generates an empty list.
public static List<T> Load<T>() where T : class,new()
{
var serializer = new DataContractSerializer(typeof(List<T>));
string path = HttpContext.Current.Server.MapPath("~/App_Data/" + typeof(T).ToString() + ".xml");
if (!System.IO.File.Exists(path))
{
return new List<T>();
}
else
{
using (var s = new System.IO.FileStream(path, System.IO.FileMode.Open))
{
return serializer.ReadObject(s) as List<T>;
}
}
}
public static void Save<T>(List<T> data) where T : class,new()
{
var serializer = new DataContractSerializer(typeof(List<T>));
Enumerate<T>(data);
string path = HttpContext.Current.Server.MapPath("~/App_Data/" + typeof(T).ToString() + ".xml");
using (var s = new System.IO.FileStream(path, System.IO.FileMode.Create))
{
serializer.WriteObject(s, data);
}
}
You might want to use JavaScriptSerializer
var json = new JavaScriptSerializer().Serialize(thing);
JSON lists are generic.
UPDATE: Ass claimed by TimS Json.NET is better serializer so if adding 3rd party library is an option here is an article on how to do it.
What about a binary serializer
public static void SerializeToBin(object obj, string filename)
{
Directory.CreateDirectory(Path.GetDirectoryName(filename));
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
bf.Serialize(fs, obj);
}
}
public static T DeSerializeFromBin<T>(string filename) where T : new()
{
if (File.Exists(filename))
{
T ret = new T();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
ret = (T)bf.Deserialize(fs);
}
return ret;
}
else
throw new FileNotFoundException(string.Format("file {0} does not exist", filename));
}
Based on what you're trying to do, the key might also be your class T, ensuring that it is decorated with the proper [DataContract] and [DataMember] attributes. Here is a working example based on your code in question (however if you don't care to be able to utilize the persisted file outside of your code, you might find better performance in the binary serializer):
[DataContract]
public class Mydata
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Mydata> myData = new List<Mydata>();
myData.Add(new Mydata() { Id = 1, Name = "Object 1" });
myData.Add(new Mydata() { Id = 2, Name = "Object 2" });
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + #"\" + typeof(Mydata).ToString() + ".xml";
Save<Mydata>(myData, path);
List<Mydata> myNewData = Load<Mydata>(path);
Console.WriteLine(myNewData.Count);
Console.ReadLine();
}
public static List<T> Load<T>(string filename) where T : class
{
var serializer = new DataContractSerializer(typeof(List<T>));
if (!System.IO.File.Exists(filename))
{
return new List<T>();
}
else
{
using (var s = new System.IO.FileStream(filename, System.IO.FileMode.Open))
{
return serializer.ReadObject(s) as List<T>;
}
}
}
public static void Save<T>(List<T> list, string filename)
{
var serializer = new DataContractSerializer(typeof(List<T>));
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs))
{
serializer.WriteObject(writer, list);
}
}
}
}