How to save a variable's data in C# Unity? [duplicate] - c#

This question already has an answer here:
Saving/loading data in Unity
(1 answer)
Closed last year.
I have a variable which I want to save the data to the user's device.
Ex: float score = 100;
I want to save this variable as data and load it on game run.

You can store your data in a external file like a json.
When you want to access your data to edit or just get the value, you can simply read/write it from the file
I advise you to use the library Newtonsoft.
Once you have downloaded the packages, add the following usings :
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
You can use this code to write in the file
/////Write in the file/////
//Create a dynamic object to store data
dynamic obj = new JObject();
//Set the values
obj.WorkDuration = workDuration;
obj.PauseDuration = pauseDuration;
obj.NbSessions = nbSessions;
//Write the values in the json file
File.WriteAllText(JsonFileFullname, JsonConvert.SerializeObject(obj));
And this code to get the data in the file
/////Get values from the file/////
//Create a reader object for get the content of the json file
StreamReader reader = new StreamReader(JsonFileFullname);
//Read the content of the json file
string json = reader.ReadToEnd();
//Create a dynamic object with stored data
dynamic data = JObject.Parse(json);
//Get the values
int workDuration = data.WorkDuration;
int pauseDuration = data.PauseDuration;
int nbSessions= data.NbSessions;
Your JSON file should look something like this
{"WorkDuration":300,"PauseDuration":5,"NbSessions":8}
I hope my answer will be of use to you. If you have any questions, don't hesitate to ask them

Related

Saving File conversion to variable instead of physical location

I'm trying out to use the XML - Mind converter https://www.xmlmind.com/foconverter/ to convert some xsl-fo to an rtf and this works well . Just to be clear this is nothing specific to the conveter or its functionality but just a clarification I would like to get which is why I am asking this on stack overflow .
So I have the following code (that was obtained from some documentation)
string foFilePath = #"D:\Temp\test.fo";
string ourPutFilePath = #"D:\Temp\test.rtf";
Converter converter = new Converter();
converter.OutputFormat = OutputFormat.Rtf;
converter.OutputEncoding = "windows-1252";
converter.ImageResolution = 120;
converter.SetInput(foFilePath);
converter.SetOutput(ourPutFilePath);
converter.Convert();
What happens here is quite simple Reads a file from the input path and stores the converted file in the specified output . The question I would like to clarify here is , wheather it would be possible to store this content that is being saved in the file out put path within a variable as well to may be do some processing during the application runtime ?
Maybe I can use the MemoryStream for it ? I'm just not sure how to do it and would really appreciate some help here.
I understand that I can always read it back from the file output path but I am looking for something better than that as saving the file to a certain location may not always be possible in my case
EDIT :- The converter.SetOutput() method allows 3 overloads in the parameters
String fileName
Stream stream
TextWriter writer
Sine you need the output as a string you could try doing something like this
string content;
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
Converter converter = new Converter();
converter.OutputFormat = OutputFormat.Rtf;
converter.OutputEncoding = "windows-1252";
converter.ImageResolution = 120;
converter.SetInput(foFilePath);
converter.SetOutput(writer);
converter.Convert();
stream.Position = 0;
content = Encoding.UTF8.GetString(stream.ToArray());
}
}
I'm not sure about the Encoding though, and if the Convert() uses a different encoding this might not work

Get a Json file from a specific folder and serialize it

I need to get json file from a specific folder in my solution. the name of the json file is "plaza.json" and the folder it is in is Data. Please see image below.
How do I get this file and serialize it? I have searched for some answers but the closest is this:
using (var streamReader = new StreamReader("plaza.json"))
{
string json = streamReader.ReadToEnd();
var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);
}
if I use that, it doesn't see my json file
using (var streamReader = new StreamReader(Server.MapPath("~/Data/plaza.json"))
{
string json = streamReader.ReadToEnd();
var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);
}
This should work, haven’t test but check this how file will be accessed
Depending on you project type it can be server.mappath or hostingenvironment.mappath
If desktop app like win forms or wpf use this
Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Data/plaza.json");
Make sure to put copy file if modified property in build property

Convert an IFile (JSON File) to MyObject

I upload a JSON file with a HTML form as explained here in the first paragraph. I accept only 1 file at a time so this is my controller:
public IActionResult Upload(IFormFile file)
{
}
Now I want to convert the file containing JSON to an object. Just like this accepted answer of Cuong Le. How do I convert the file to lets say MyObject? How do i deserialize the file?
(Newtonsoft is the lib to import right?)
You can read the text from the file and then convert to JSON. You can try something like,
string fileContent = null;
using (var reader = new StreamReader(file.OpenReadStream()))
{
fileContent = reader.ReadToEnd();
}
var result = JsonConvert.DeserializeObject<MyObject>(fileContent );
Yes, you can use Newtonsoft NuGet package for deserializing.

How to get string from dataPackageView.GetDataAsync()

I'm trying to get non-standard-format data from the clipboard using DataPackageView.GetDataAsync. I am stumped on converting the returned system.__ComObject to a string.
Here is the code:
var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
if (dataPackageView.Contains("FileName"))
{
var data = await dataPackageView.GetDataAsync("FileName");
// How to convert data to string?
}
I am looking for a solution that will work with any non-standard clipboard format. "FileName" is an easily testable format as you can put it on the clipboard by copying a file in Windows Explorer.
In C++/Win32, I can get the clipboard data as follows:
OpenClipboard(nullptr);
UINT clipboarFormat = RegisterClipboardFormat(L"FileName");
HANDLE hData = GetClipboardData(clipboarFormat);
char * pszText = static_cast<char*>(GlobalLock(hData));
GlobalUnlock(hData);
CloseClipboard();
In C++, the clipboard data is just an array of bytes. It must be possible to get the same array of bytes in C#, but I have no clue on unwrapping/converting the system.__ComObject
Edit: Rephrasing the question:
How do I get a string or array of byes out of the system.__ComObject returned by dataPackageView.GetDataAsync(someFormat), where someFormat is an arbitrary clipboard format created by another application?
It is very clear to me how to get the data. The difficult part is using the data that is returned.
The accepted answer must show how to create a string or array of bytes from the "data" returned by
var data = await dataPackageView.GetDataAsync(someFormat);
if you know its a file you can use the following code
var content = Clipboard.GetContent();
IReadOnlyList<IStorageItem> files = await content.GetStorageItemsAsync();
var file = files.First() as StorageFile;
From MSDN article on StandardDataFormats
The DataPackage class supports a number of legacy formats for interoperability between Windows Store apps and desktop apps. To retrieve these formats, you pass one of the following strings to the DataPackageView.GetDataAsync method instead of a value from the StandardDataFormats class.
eg
var content = Clipboard.GetContent();
var data = await content.GetDataAsync("PenData"); //Stream for HGLOBAL corresponding to CF_PENDATA
This article explains how custom dataPackage objects are implemented.
http://www.minddriven.de/index.php/technology/dot-net/c-sharp/winrt-datapackage-custom-objects
The key is to cast the return value of dataPackageView.GetAsync() into an IRandomAccessStream
Here is something that works:
var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
if (dataPackageView.Contains("FileName"))
{
var data = await dataPackageView.GetDataAsync("FileName");
// convert data to string
var data = await dataPackageView.GetDataAsync("FileName");
var dataObj = data as IRandomAccessStream;
var stream = dataObj.GetInputStreamAt(0);
IBuffer buff = new Windows.Storage.Streams.Buffer((uint)dataObj.Size);
await stream.ReadAsync(buff, (uint)dataObj.Size, InputStreamOptions.None);
var filePath = Encoding.ASCII.GetString(buff.ToArray());
filePath = filePath.Replace("\0","");//get rid of null characters
}
This should work for any custom data format, not just "FileName". If you do not require a string, you could just use the bytes available from the IRandomAccessStream.

Getting Json Output from Byte Array

I just started a new project on WCF and to be honest I'm very new at this with limited knowledge.
So what I'm trying to do is open a file that is stored in my computer (e.g. word, pdf, etc.) and display the contents in the webpage in JSon format. I converted the file in a byte array and tried to display the Stream. When I did that it asked me to open the file or save it. I don't want that - I just want the contents of the file to be displayed on my local host when i call the method.
Here's what I have:
public string GetRawFile()
{
string file = #"C:\.....\TestFile.pdf";
byte[] rawFile = File.ReadAllBytes(file);
//Stream stream = new MemoryStream(rawFile);
//DataContractJsonSerializer obj = newDataContractJsonSerializer(typeof(string));
//string result = obj.ReadObject(stream).ToString();
//Deserializing
MemoryStream stream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
stream.Write(rawFile, 0, rawFile.Length);
stream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(stream);
System.Web.Script.Serialization.JavaScriptSerializer xyz = new System.Web.Script.Serialization.JavaScriptSerializer();
string ejson = xyz.Serialize(obj);
WebOperationContext.Current.OutgoingRequest.ContentType = "text/json";
return ejson;
}
I'm trying to return a string and it's not working, but when I return just the stream it's popping up the "openwith" message.
Also should I use the GET or POST on my datacontract. I'm using REST in C#.
I'm assuming that your file actually contains json. If that is the case just do this;
string file = File.ReadAllText("C:\path\to\file.extension");
You're making the problem a lot more complicated than it needs to be. Just read the file and return it's data as a string. I think you want to use GET for the http method. Generally speaking, you all use post if you're adding new content. If for example the users request would cause the application to write some data to a file or data base then you would typically use POST for the http method. If they're just requesting data, you almost always use GET.

Categories