I currently have this code.
This is the code I actually use to read the file:
public ObservableCollection<Esame> rigaEsame = new ObservableCollection<Esame>();
private void ReadFile()
{
Esami.ItemsSource = rigaEsame;
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("exams.txt", FileMode.OpenOrCreate, FileAccess.Read);
string tmp;
string tmp2;
using (StreamReader reader = new StreamReader(fileStream))
{
while (!reader.EndOfStream)
{
tmp = reader.ReadLine();
tmp2 = reader.ReadLine();
rigaEsame.Insert(0, new Esame(tmp,tmp2));
Debug.WriteLine(tmp);
}
}
}
This code is the one I use to write to the file:
private void InsertEntry_click(object sender, RoutedEventArgs e)
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("exams.txt", FileMode.Append, FileAccess.Write, myIsolatedStorage)))
{
writeFile.WriteLine(Subject.Text);
writeFile.WriteLine(Date.Text);
writeFile.Close();
}
NavigationService.Navigate(new Uri("/Views/MainPage.xaml",UriKind.Relative));
}
and this is the class file:
public class Esame
{
public string nomeEsame { get; set; }
public string descrizioneEsame { get; set; }
public string Name
{
get { return nomeEsame; }
set { nomeEsame = value; }
}
public Esame(string esame, string descrizione)
{
nomeEsame = esame;
descrizioneEsame = descrizione;
}
}
I am currently able to write the text from the TextBlock "Subject" and place it into my "Esami" LongListSelector. Still, I am currently unable to correctly read/write the second text string, coming from the TextBlock named "Date".
How may I do that? I suppose there is something wrong with the class itself or the way I use it when putting it into my LongListSelector list item.
How may i fix that?
Related
public class Program
{
static void Main()
{
var resuult = ReaderHelper.ReadFromFile(#"C:\Users\xalva\source\repos\pokerstars\Aletta.txt");
Console.WriteLine(resuult);
Reader reader = new Reader(resuult, 0);
}
}
static class ReaderHelper
{
public static string ReadFromFile(string filePath)
{
string pokerText;
using (FileStream pokerHand = File.OpenRead(filePath))
{
byte[] array = new byte[pokerHand.Length];
pokerHand.Read(array, 0, array.Length);
pokerText = System.Text.Encoding.Default.GetString(array);
}
return pokerText;
}
public class Reader
{
static int Cursor { get; set; }
static string Buffer { get; set; }
public Reader(string buffer, int cursor)
{
Cursor = cursor;
Buffer = buffer;
}
I have a little project where i have to get some information from text file about draw of poker hands.
In class ReaderHelper I get information from a text file, then I create an object of the Reader class and get null in the Buffer. Why so?(It's not all code)
You can just use File.ReadAllText("[...]") to read text from a file:
static void Main()
{
var result = File.ReadAllText(#"C:\Users\xalva\source\repos\pokerstars\Aletta.txt");
Console.WriteLine(result);
Reader reader = new Reader(result, 0);
}
or you can use a StreamReader object, if you want to use streams, to read text:
public static string ReadFromFile(string filePath)
{
string pokerText;
using (FileStream pokerHand = File.OpenRead(filePath))
using (StreamReader sr = new StreamReader(pokerHand))
{
pokerText = sr.ReadToEnd();
}
return pokerText;
}
I have tried alot of solution but no one is working in my case, my question is simple but i cant find any answer specially for windows build. I have tried to load json form persistent , streaming and resource all are working good in android but no any solution work for windows build. here is my code please help me.
public GameData gameData;
private void LoadGameData()
{
string path = "ItemsData";
TextAsset targetFile = Resources.Load<TextAsset>(path);
string json = targetFile.text;
gameData = ResourceHelper.DecodeObject<GameData>(json);
// gameData = JsonUtility.FromJson<GameData>(json);
print(gameData.Items.Count);
}
here is my data class
[Serializable]
public class GameData
{
[SerializeField]
public List<Item> Items;
public GameData()
{
Items = new List<Item>();
}
}
public class Item
{
public string Id;
public string[] TexturesArray;
public bool Active;
public Item()
{
}
public Item(string _id, string[] _textureArray , bool _active = true)
{
Id = _id;
TexturesArray = _textureArray;
Active = _active;
}
}
In order to be (de)serialized Item should be [Serializable]
using System;
...
[Serializable]
public class Item
{
...
}
Then you could simply use Unity's built-in JsonUtility.FromJson:
public GameData gameData;
private void LoadGameData()
{
string path = "ItemsData";
TextAsset targetFile = Resources.Load<TextAsset>(path);
string json = targetFile.text;
gameData = JsonUtility.FromJson<GameData>(json);
print(gameData.Items.Count);
}
For loading something from e.g. persistentDataPath I always use something like
var path = Path.Combine(Application.persistentDataPath, "FileName.txt")
using (var fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var sr = new StreamReader(fs))
{
var json = sr.ReadToEnd();
...
}
}
For development I actually place my file into StreamingAssets (streamingAssetsPath) while running the code in the Unity Editor.
Then on runtime I read from persistentFilePath. If the file is not there I first copy it from the streamingassetsPath the first time.
Here I wrote more about this approach
I have a class like this:
public class Response
{
public String AdditionalData = "";
public Boolean Success = false;
public int ErrorCode = 0;
public int WarningCode = 0;
public Transaction TransactionInfo = null;
public PosInfo PosInformation = null;
}
and i can serialize this successfully. but when i serialize this class 2 times and save it in a XML file,multi root error appear in XML editor. i know it needs a XML element to be root to surround other tags, but i don't know how to add root element in a serialize code.
sterilizer class is below:
public class Serializer
{
public void XMLSerializer(Response response)
{
string path = "D:/Serialization.xml";
FileStream fs;
XmlSerializer xs = new XmlSerializer(typeof(Response));
if(!File.Exists(path))
{
fs = new FileStream(path, FileMode.OpenOrCreate);
}
else
{
fs = new FileStream(path, FileMode.Append);
}
StreamWriter sw = new StreamWriter(fs);
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = System.Xml.Formatting.Indented;
xs.Serialize(xw, response);
xw.Flush();
fs.Close();
}
}
I would recommend improving your code to at least take care of disposable resources.
using Statement
Provides a convenient syntax that ensures the correct use of IDisposable objects.
public class Serializer
{
public void XMLSerializer(Response response)
{
string path = "D:/Serialization.xml";
var xs = new XmlSerializer(typeof(Response));
using (var fs = new FileStream(path, FileMode.OpenOrCreate))
{
using (var sw = new StreamWriter(fs))
{
using (var xw = new XmlTextWriter(sw))
{
xw.Formatting = System.Xml.Formatting.Indented;
xs.Serialize(xw, response);
xw.Flush();
}
}
fs.Close();
}
}
}
Hey guys I am working on a program that will take a person's name and comment and then serialize it to a binary file. It must also be able to deserialize and load the data to the form. I need it to be able to go up and down the list of files(names and comments) by using buttons on the form.
In my code I have it separated into a class that builds the object and the code for the form, and no i'm not allowed to separate it. (Just in case anyone thought that'd work)
the form code:
private void btnAdd_Click(object sender, EventArgs e)
{
bool blnValid = true;
if (string.IsNullOrWhiteSpace(txtName.Text))
{
MessageBox.Show("Please enter a valid name");
}
if (string.IsNullOrWhiteSpace(txtComment.Text))
{
MessageBox.Show("Please enter a valid comment");
blnValid = false;
}
if (blnValid)
{
//create class instance and assign property values
//set file name
DateTime CurrentDate = DateTime.Now;
string strFileName;
strFileName = CurrentDate.ToString("dd-MM-yy-hh-mm-ss") + ".bin";
// serialize object to binary file
MessageBox.Show(strFileName);
Enquiry newEnquiry = new Enquiry();
newEnquiry.Name = txtName.Text;
newEnquiry.Comment = txtComment.Text;
newEnquiry.DOB = dteDOB.Value;
newEnquiry.WriteToFile(strFileName, newEnquiry);
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
}
private void btnPrevious_Click(object sender, EventArgs e)
{
}
and the class code:
[Serializable]
class Enquiry
{
//stores the various values into the enquiry class.
public string Name { get; set; }
public DateTime DOB { get; set; }
public string Comment { get; set; }
//creates the file, if there isn't one, writes the file, and
//disables sharing while the program is active. It also formats
//the file into binary
public void WriteToFile(string strFileName, Enquiry newEnquiry)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(strFileName, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, newEnquiry);
stream.Close();
}
// this loads the files and translates them to plain text
public void ReadFromFile(string strFileName, Enquiry newEnquiry)
{
Stream stream = File.OpenRead(strFileName);
BinaryFormatter formatter = new BinaryFormatter();
newEnquiry = (Enquiry)formatter.Deserialize(stream);
stream.Close();
}
I don't know what you are asking, but if you need methods to serialize and deserialize, use these:
public static void BinarySerializeObject(string path, object obj)
{
using (StreamWriter streamWriter = new StreamWriter(path))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
try
{
binaryFormatter.Serialize(streamWriter.BaseStream, obj);
}
catch (SerializationException ex)
{
throw new SerializationException(((object) ex).ToString() + "\n" + ex.Source);
}
}
}
public static object BinaryDeserializeObject(string path)
{
using (StreamReader streamReader = new StreamReader(path))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
object obj;
try
{
obj = binaryFormatter.Deserialize(streamReader.BaseStream);
}
catch (SerializationException ex)
{
throw new SerializationException(((object) ex).ToString() + "\n" + ex.Source);
}
return obj;
}
}
im stuck with this stupid form... heres my code. It saves it where the streamwriter wants it to but when i save it where the user wants via the savedialog box is creates the XML but doesnt put anything in it! Can someone have a look as it's starting to wind me up!
void SavebuttonClick(object sender, EventArgs e)
{
Stream myStream ;
SaveFileDialog savefile1 = new SaveFileDialog();
savefile1.Filter = "xml files |*.xml" ;
savefile1.FilterIndex = 2 ;
savefile1.RestoreDirectory = true ;
if(savefile1.ShowDialog() == DialogResult.OK)
{
if((myStream = savefile1.OpenFile()) != null)
{
Values v = new Values();
v.task1_name = this.task1_name.Text;
v.task1_desc = this.task1_desc.Text;
v.task1_date = this.task1_date.Value;
v.task1_time = this.task1_time.Value;
SaveValues(v);
}
myStream.Close();
}
}
This is the streamwriter...
public void SaveValues(Values v)
{
XmlSerializer serializer = new XmlSerializer(typeof(Values));
using(TextWriter textWriter = new StreamWriter(#"E:\TheFileYouWantToStore.xml"))
{
serializer.Serialize(textWriter, v);
}
...
}
EDIT:
public class Values
{
public string task1_name { get; set;}
public string task1_desc { get; set;}
public DateTime task1_date { get; set;}
public DateTime task1_time { get; set;}
}
I presume this is the code you meant, im fairly new to coding though mate :(
You must call textWriter.close(); after serialize. If you don't close writer it won't apply chenges to file.
By the way you are writing values to E:\TheFileYouWantToStore.xml. your save save method does not use users file.
public void SaveValues(Values v)
{
XmlSerializer serializer = new XmlSerializer(typeof(Values));
using(TextWriter textWriter = new StreamWriter(#"E:\TheFileYouWantToStore.xml"))
{
serializer.Serialize(textWriter, v);
textWriter.close();
}
...
}
EDIT:
if(savefile1.ShowDialog() == DialogResult.OK)
{
Values v = new Values();
v.task1_name = this.task1_name.Text;
v.task1_desc = this.task1_desc.Text;
v.task1_date = this.task1_date.Value;
v.task1_time = this.task1_time.Value;
SaveValues(savefile1.FileName, v);
}
-
public void SaveValues(string fileName, Values v)
{
XmlSerializer serializer = new XmlSerializer(typeof(Values));
using(TextWriter textWriter = new StreamWriter(fileName))
{
serializer.Serialize(textWriter, v);
textWriter.close();
}
...
}