This error is showing up in my code, there is a second one that is as follows:
XmlException: The existing data at the root level is invalid. Line 1, position 1
I checked this second one saying there is a error with the file when there isn't any since I have 5 files inside my XMLFiles directory.
public static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(ImportSession));
MemoryStream stream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(stream);
sw.Flush();
stream.Position = 0;
}
Console.ReadKey();
foreach (string filename in Directory.EnumerateFiles(#"C:\XMLFiles", "*.xml"))
{
ProcessFile(filename, stream, serializer);
}
void ProcessFile(string Filename, MemoryStream stream, XmlSerializer serializer)
{
bool temErro = false;
Console.WriteLine("A processar xml: " + Filename);
XmlDocument xml = new XmlDocument();
xml.Load(Filename);
ImportSession session = (ImportSession)serializer.Deserialize(stream);
foreach (Batch batch in session.Batches)
{
foreach (Document doc in batch.Documents)
{
foreach (Page page in doc.Pages)
{
if (!string.IsNullOrEmpty(batch.Processed.ToString()))
{
if (!string.IsNullOrEmpty(page.HasError.ToString()))
{
string Import = page.ImportFileName;
Console.WriteLine("Página com erro:" + Import);
temErro = true;
}
}
}
}
}
if (temErro)
Console.WriteLine("Ficheiro com erro: " + Filename);
else
Console.WriteLine("Ficheiro processado: " + Filename);
Console.WriteLine(Filename);
}
}
public class ImportSession
{
public Batch[] Batches { get; set; }
}
public class Batch
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Description { get; set; }
[XmlAttribute]
public string BatchClassName { get; set; }
[XmlAttribute]
public bool Processed { get; set; }
public Document[] Documents { get; set; }
}
public class Document
{
[XmlAttribute]
public string FormTypeName { get; set; }
public IndexField[] IndexFields { get; set; }
public Page[] Pages { get; set; }
}
public class IndexField
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Value { get; set; }
}
public class Page
{
[XmlAttribute]
public string ImportFileName { get; set; }
[XmlAttribute]
public string ErrorCode { get; set; }
[XmlAttribute]
public string ErrorMessage { get; set; }
[XmlIgnore]
public bool HasError => !string.IsNullOrWhiteSpace(ErrorMessage);
}
This app right now is only trying to read all the files and point out some parts that need to show up in the console and it was doing it but I was adviced on here to change into this object oriented and memory stream.
This:
MemoryStream stream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(stream);
sw.Flush();
stream.Position = 0;
is basically meaningless. Whatever the contents of stream are meant to be: it isn't this. Ask yourself:
What is stream meant to contain?
At the moment it contains... itself, sort of, but not really?
If you intend the stream to be the file contents: just use File.OpenRead
I think this is based on a misunderstanding from answers to previous questions on the topic.
This should make it work. BUT keep in mind, that it is in no way production-ready.
public static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(ImportSession));
foreach (string filename in Directory.EnumerateFiles(#"C:\XMLFiles", "*.xml"))
{
ProcessFile(filename, serializer);
}
Console.ReadKey();
}
private static void ProcessFile(string Filename, XmlSerializer serializer)
{
bool temErro = false;
Console.WriteLine("A processar xml: " + Filename);
using (var file = File.OpenRead(Filename)) {
var session = (ImportSession)serializer.Deserialize(file);
// from here on the rest of your code ...
To minimize the code that keeps the file opened:
ImportSession session;
using (var file = File.OpenRead(Filename))
{
session = (ImportSession)serializer.Deserialize(file);
}
// file will be closed by disposal of FileStream using this notation
// rest of code
Addendum
if (!string.IsNullOrEmpty(batch.Processed.ToString()))
{ // Will ALWAYS be entered!
if (!string.IsNullOrEmpty(page.HasError.ToString()))
{ // Will ALWAYS be entered!
string Import = page.ImportFileName;
Console.WriteLine("Página com erro:" + Import);
temErro = true;
}
}
Let's look at it:
!string.IsNullOrEmpty(page.HasError.ToString()) is always true. Why?
page.HasError is of type bool. So, page.HasError.ToString() "Converts the value of this instance to its equivalent string representation (either "True" or "False")."
So, it will never be null or empty. So, string.IsNullOrEmpty will always be false, and !string.IsNullOrEmpty therefore always be true.
If you want to check the boolean value, you simply do if( page.HasError ) => "Page has an error"
My class structure is as follows:
class AppDetails
{
public String companyName { get; set; }
public String applicationName { get; set; }
public String version { get; set; }
public List<File_> fileObjectList { get; set; }
public AppDetails(String cName, String aName, String v)
{
companyName = cName;
applicationName = aName;
version = v;
}
}
class File_
{
public String filePath { get; set; }
public FileRecord fileRecord { get; set; }
public File_(String parent_, String filepath_, Boolean Ignored)
{
filePath = filepath_;
fileRecord = new FileRecord(parent_ + filePath, Ignored);
}
}
class FileRecord
{
public Boolean ignored { get; set; }
public String MD5Checksum { get; set; }
public int version { get; set; }
public FileRecord(String filePath, Boolean ignored_)
{
ignored = ignored_;
if (ignored)
{
MD5Checksum = null;
}
else
{
MD5Checksum = CalculateMD5(filePath);
version = 0;
}
}
static string CalculateMD5(string filePath)
{
var md5 = MD5.Create();
var stream = File.OpenRead(filePath);
var hash = md5.ComputeHash((System.IO.Stream)stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
I generated Json file using these classes. But when I try to initialize an object with the said JSON file, it throws System.ArgumentNullException: 'Path cannot be null. Parameter name: path' exception.
This is the function that is supposed to return the object.
AppDetails ReadJsonFile()
{
using (StreamReader r = File.OpenText(parent + "\\AllFilesList.json"))
{
string json = r.ReadToEnd();
var result = JsonConvert.DeserializeObject<AppDetails>(json);
return result;
}
}
I tried generating the classes from JSON using online class generators and it matches my class structure. Exception is thrown on this line:
var result = JsonConvert.DeserializeObject<AppDetails>(json);
Json string is getting loaded with the content from the file just fine(as can be seen from the watch). I couldn't find anything about Path issues related to JsonConvert.DeserializeObject. Most previous questions seems to be related to value errors.
EDIT: Serialization Code
void JsonWriter(AppDetails appDetails, String filename)
{
string path = parent + "\\" + filename + ".json";
File.Delete(path);
string json = JsonConvert.SerializeObject(appDetails);
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(json.ToString());
tw.Close();
}
}
Sample Json File:
{"companyName":"Home","applicationName":"Test","version":"V5.0.1","fileObjectList":[{"filePath":"\\bug-tracker.exe","fileRecord":{"ignored":false,"MD5Checksum":"a5254a813a040b429f2288df737a8b9f","version":0}},{"filePath":"\\bug-tracker.exe.config","fileRecord":{"ignored":false,"MD5Checksum":"e5c3e9137dc8fadb57dfc27b0ba6855c","version":0}},{"filePath":"\\bug-tracker.pdb","fileRecord":{"ignored":false,"MD5Checksum":"9a9dfda29dcaacae82cba7bd7aa97ffa","version":0}},{"filePath":"\\Caliburn.Micro.dll","fileRecord":{"ignored":false,"MD5Checksum":"aa5f96c02b08d9b33322f3024058dd91","version":0}},{"filePath":"\\Caliburn.Micro.Platform.Core.dll","fileRecord":{"ignored":false,"MD5Checksum":"ab7867bd44b59879a59b5cb968e15668","version":0}},{"filePath":"\\Caliburn.Micro.Platform.Core.xml","fileRecord":{"ignored":false,"MD5Checksum":"cdfcbbf70a9a62b92e82a953ab9e7e30","version":0}},{"filePath":"\\Caliburn.Micro.Platform.dll","fileRecord":{"ignored":false,"MD5Checksum":"a52bdecbc1b7625cb13c9385fad4231b","version":0}},{"filePath":"\\Caliburn.Micro.Platform.xml","fileRecord":{"ignored":false,"MD5Checksum":"09f258a3aeca7285355d82a66dda2176","version":0}},{"filePath":"\\Caliburn.Micro.xml","fileRecord":{"ignored":false,"MD5Checksum":"c87ec582a4bfcf2e79e517c689441def","version":0}},{"filePath":"\\MaterialDesignColors.dll","fileRecord":{"ignored":false,"MD5Checksum":"ad729352a9088b889cc0c4dc7542dcb6","version":0}},{"filePath":"\\MaterialDesignColors.pdb","fileRecord":{"ignored":false,"MD5Checksum":"7ba70b23e22db9ac155e190860d9a5ec","version":0}},{"filePath":"\\MaterialDesignThemes.Wpf.dll","fileRecord":{"ignored":false,"MD5Checksum":"e4c790d3af41620dc5ad513ae7fcadac","version":0}},{"filePath":"\\MaterialDesignThemes.Wpf.pdb","fileRecord":{"ignored":false,"MD5Checksum":"f8113c8ea54896b8150db8e7ebd506ef","version":0}},{"filePath":"\\MaterialDesignThemes.Wpf.xml","fileRecord":{"ignored":false,"MD5Checksum":"49717f8130b7529ee51fb6bc13f79aa4","version":0}},{"filePath":"\\ShowMeTheXAML.dll","fileRecord":{"ignored":false,"MD5Checksum":"040b9e80820553a55f13ac19c2036367","version":0}},{"filePath":"\\System.Windows.Interactivity.dll","fileRecord":{"ignored":false,"MD5Checksum":"580244bc805220253a87196913eb3e5e","version":0}}]}
Edit 2: Json String from watch
"{\"companyName\":\"Home\",\"applicationName\":\"Test\",\"version\":\"V5.0.1\",\"fileObjectList\":[{\"filePath\":\"\\\\bug-tracker.exe\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"a5254a813a040b429f2288df737a8b9f\",\"version\":0}},{\"filePath\":\"\\\\bug-tracker.exe.config\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"e5c3e9137dc8fadb57dfc27b0ba6855c\",\"version\":0}},{\"filePath\":\"\\\\bug-tracker.pdb\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"9a9dfda29dcaacae82cba7bd7aa97ffa\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"aa5f96c02b08d9b33322f3024058dd91\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.Platform.Core.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"ab7867bd44b59879a59b5cb968e15668\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.Platform.Core.xml\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"cdfcbbf70a9a62b92e82a953ab9e7e30\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.Platform.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"a52bdecbc1b7625cb13c9385fad4231b\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.Platform.xml\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"09f258a3aeca7285355d82a66dda2176\",\"version\":0}},{\"filePath\":\"\\\\Caliburn.Micro.xml\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"c87ec582a4bfcf2e79e517c689441def\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignColors.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"ad729352a9088b889cc0c4dc7542dcb6\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignColors.pdb\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"7ba70b23e22db9ac155e190860d9a5ec\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignThemes.Wpf.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"e4c790d3af41620dc5ad513ae7fcadac\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignThemes.Wpf.pdb\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"f8113c8ea54896b8150db8e7ebd506ef\",\"version\":0}},{\"filePath\":\"\\\\MaterialDesignThemes.Wpf.xml\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"49717f8130b7529ee51fb6bc13f79aa4\",\"version\":0}},{\"filePath\":\"\\\\ShowMeTheXAML.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"040b9e80820553a55f13ac19c2036367\",\"version\":0}},{\"filePath\":\"\\\\System.Windows.Interactivity.dll\",\"fileRecord\":{\"ignored\":false,\"MD5Checksum\":\"580244bc805220253a87196913eb3e5e\",\"version\":0}}]}\r\n"
The actual issue is that you have the parameters in your constructor:
public FileRecord(String filePath, Boolean ignored_)
And JsonConvert puts there default values (null, false) which triggers the code:
else
{
MD5Checksum = CalculateMD5(filePath);
version = 0;
}
Which in its turn tries to read from a file using null path parameter:
static string CalculateMD5(string filePath)
{
var md5 = MD5.Create();
var stream = File.OpenRead(filePath); // <- HERE!!!!
var hash = md5.ComputeHash((System.IO.Stream)stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
I see there two solutions
Create parameterless constructors where init everything as you need or call the constructor with parameters using :this() with defaults:
public FileRecord() : this(null, true)
{
}
Rename properties to match parameter names, like:
public bool Ignored { get; set; }
public FileRecord(string filePath, bool ignored)
{
this.Ingnoerd = ignored;
....
}
I have been trying to create a simple csv file using the csv helper. However, the result, I am getting is not what I expected.
For some reason which I cannot find it, the first value is shifting towards the right and appear as the header.
Could someone point me what I am doing wrong here?
public class Record
{
public string Vrm { get; set; }
public string Version { get; set; }
public DateTime Started { get; set; }
public DateTime? Completed { get; set; }
public string Status { get; set; }
public string Comments { get; set; }
}
static void Main(string[] args)
{
var source = new List<Record> {
new Record {
Status = "Success",
Version = "enhance",
Started = DateTime.Parse("2017-11-15 13:27:56.9933333"),
Completed = DateTime.Parse("2017-11-15 13:27:57.7300000"),
Vrm = "16aux",
Comments = "Completed Successfully"
}
};
var month = DateTime.UtcNow.Month;
var year = DateTime.UtcNow.Year;
var fileName = $"TestFile_{month}{year}.csv";
using (var sw = new StreamWriter(fileName))
{
var writer = new CsvWriter(sw);
try
{
writer.WriteHeader<Record>();
foreach (var record in source)
{
writer.WriteField(record.Vrm);
writer.WriteField(record.Version);
writer.WriteField(record.Started);
writer.WriteField(record.Completed);
writer.WriteField(record.Status);
writer.WriteField(record.Comments);
writer.NextRecord();
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
var i = sw;
}
}
The result is something like this:
Read up on http://joshclose.github.io/CsvHelper/writing#writing-all-records
You need to advance the writer one line by calling writer.NextRecord(); after writer.WriteHeader<Record>();.
You could also simply write all data at once, using csv.WriteRecords( records ); instead of foreaching over them
From this code. I want to parse only value from the json file
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
using (StreamReader file = File.OpenText(openFileDialog1.FileName))
using (JsonTextReader reader = new JsonTextReader(file))
{
while (reader.Read())
{
if (reader.Value != null)
{
richTextBox1.Text = reader.Value.ToString();
}
else
{
MessageBox.Show("Error while parsing json file. Please try again.");
}
}
}
}
And the value is
{
"install.and": "a",
"install.emailAddress": "E-mailová adresa",
"install.emailIncorrect": "Zadejte platnou e-mailovou adresu.",
"install.emailRetryPrefix": "Neobdrželi jste e-mail? Zkuste to znovu",
"install.emailRetry": "Zkuste to znovu",
"install.emailSend": "Odeslat odkaz",
"install.emailSent": "E-mail byl odeslán!",
"install.emailSentTo": "E-mail byl odeslán",
"install.emailText1": "Můžete navštívit",
"install.emailText2": "Pokud nám poskytnete e-mailovou adresu, budeme vám moci poslat odkaz na pozdější instalaci.",
"install.installing": "Instalace...",
"install.later": "Instalovat později",
"install.licenseAgreement": "licenční smlouva",
"install.privacyPolicy": "zásady ochrany osobních údajů",
"install.quit": "Ukončit instalační program"
}
I want to parse it after : symbol. (Is it value?) to show in richTextbox as Text.
Try this code
using (StreamReader file = File.OpenText(openFileDialog1.FileName))
using (JsonTextReader reader = new JsonTextReader(file))
{
var o = JObject.Load(reader);
foreach (var v in o)
{
var value = v.Value.Value<string>();
//do whatever you want with value
}
}
If you want only values joined by newline, then try this one
using (StreamReader file = File.OpenText(openFileDialog1.FileName))
using (JsonTextReader reader = new JsonTextReader(file))
{
var o = JObject.Load(reader);
var e = o.Values().Select(x => x.Value<string>());
var values = string.Join(Environment.NewLine, e);
//do whatever you want with values
}
Introduce two temporary variable to hold key and value
string key = string.Empty;
string value = string.Empty;
Modify your while loop like this,
using (JsonTextReader reader = new JsonTextReader(file))
{
while (reader.Read())
{
if (reader.Value != null)
{
key = reader.Value.ToString();
if (reader.Read())
value = reader.Value.ToString();
Console.WriteLine("{0} : {1}", key,value);
//Instead of writing in a console, process and write it in Rich text box.
}
}
}
You can use Json.Net and create a model :
public class JsonObject
{
[JsonProperty("install.and")]
public string install_and { get; set; }
[JsonProperty("install.emailAddress")]
public string emailAddress { get; set; }
[JsonProperty("install.emailIncorrect")]
public string emailIncorrect { get; set; }
[JsonProperty("emailRetryPrefix")]
public string emailRetryPrefix { get; set; }
[JsonProperty("install.emailRetry")]
public string emailRetry { get; set; }
[JsonProperty("install.emailSend")]
public string emailSend { get; set; }
[JsonProperty("install.emailSent")]
public string emailSent { get; set; }
[JsonProperty("install.emailSentTo")]
public string emailSentTo { get; set; }
[JsonProperty("install.emailText1")]
public string emailText1 { get; set; }
[JsonProperty("install.emailText2")]
public string emailText2 { get; set; }
[JsonProperty("install.installing")]
public string installing { get; set; }
[JsonProperty("install.later")]
public string later { get; set; }
[JsonProperty("install.licenseAgreement")]
public string licenseAgreement { get; set; }
[JsonProperty("install.privacyPolicy")]
public string privacyPolicy { get; set; }
[JsonProperty("install.quit")]
public string quit { get; set; }
}
Then you can prase you json file:
string json_data = "{\"install.and\": \"a\",\"install.emailAddress\": \"E-mailová adresa\",\"install.emailIncorrect\": \"Zadejte platnou e-mailovou adresu.\",\"install.emailRetryPrefix\": \"Neobdrželi jste e-mail? Zkuste to znovu\",\"install.emailRetry\": \"Zkuste to znovu\",\"install.emailSend\": \"Odeslat odkaz\",\"install.emailSent\": \"E-mail byl odeslán!\",\"install.emailSentTo\": \"E-mail byl odeslán\",\"install.emailText1\": \"Můžete navštívit\",\"install.emailText2\": \"Pokud nám poskytnete e-mailovou adresu, budeme vám moci poslat odkaz na pozdější instalaci.\",\"install.installing\": \"Instalace...\",\"install.later\": \"Instalovat později\",\"install.licenseAgreement\": \"licenční smlouva\",\"install.privacyPolicy\": \"zásady ochrany osobních údajů\",\"install.quit\": \"Ukončit instalační program\"";
JsonObject data = JsonConvert.DeserializeObject<JsonObject>(json_data);
richTextBox1.Text = data.emailAddress;
richTextBox2.Text = data.emailIncorrect;
richTextBox3.Text = data.emailRetry;
[...]
First, Install newtonsoft.json from nuget package manager. Add the namespace
using Newtonsoft.Json.Linq;
create a class to easily handle the values.
class Details
{
public string and;
public string EmailAddress;
public string EmailIncorrect;
public string EmailRetry;
public string EmailSend;
public string EmailSent;
}
Then read the file into a string and parse it using JObject.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string file = File.ReadAllText(openFileDialog1.FileName);
JObject jo = JObject.Parse(file);
Details dt = new Details();
dt.and = (string)jo["install.and"];
richTextBox1.Text = reader.Value.ToString();
}
I have the following code:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog.AddExtension = true;
saveFileDialog.DefaultExt = ".xml";
var resultDialog = saveFileDialog.ShowDialog(this);
if (resultDialog == System.Windows.Forms.DialogResult.OK)
{
string fileName = saveFileDialog.FileName;
SerializeObject(ListaDeBotoes, fileName);
}
}
public void SerializeObject(List<MyButton> serializableObjects, string fileName)
{
if (serializableObjects == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObjects.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObjects);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
stream.Close();
}
}
catch (Exception ex)
{
//Log exception here
}
}
My objective is to save this list of MyButtons, that is my own class (it is a control too if this matter), in a way that i could re-open it on the future. But this way is not working it stops at: XmlSerializer serializer = new XmlSerializer(serializableObjects.GetType()); and the catch exception is called... Any suggestions?
Try this....
Usings.....
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
Functions....
private void Serialize<T>(T data)
{
// Use a file stream here.
using (TextWriter WriteFileStream = new StreamWriter("test.xml"))
{
// Construct a SoapFormatter and use it
// to serialize the data to the stream.
XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
try
{
// Serialize EmployeeList to the file stream
SerializerObj.Serialize(WriteFileStream, data);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
}
}
}
private T Deserialize<T>() where T : new()
{
//List<Employee> EmployeeList2 = new List<Employee>();
// Create an instance of T
T ReturnListOfT = CreateInstance<T>();
// Create a new file stream for reading the XML file
using (FileStream ReadFileStream = new FileStream("test.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Construct a XmlSerializer and use it
// to serialize the data from the stream.
XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
try
{
// Deserialize the hashtable from the file
ReturnListOfT = (T)SerializerObj.Deserialize(ReadFileStream);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
}
}
// return the Deserialized data.
return ReturnListOfT;
}
// function to create instance of T
public static T CreateInstance<T>() where T : new()
{
return (T)Activator.CreateInstance(typeof(T));
}
Usage....
Serialize(dObj); // dObj is List<YourClass>
List<YourClass> deserializedList = Deserialize<List<YourClass>>();
Your object will be written\read to\from a file called test.xml that you can modify to suit....
Hope that helps....
/////////////////////////////////////////////////////////////////////////
An example class to hold your values for each MyButton object might look something like this......
public partial class PropertiesClass
{
public string colorNow { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.Black.ToArgb()));
public string backgroundColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.Black.ToArgb()));
public string externalLineColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.DarkBlue.ToArgb()));
public string firstColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.Goldenrod.ToArgb()));
public string secondColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.DarkGoldenrod.ToArgb()));
public string mouseEnterColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.PaleGoldenrod.ToArgb()));
public string doubleClickColor { get; set; } = ColorTranslator.ToHtml(Color.FromArgb(Color.Gold.ToArgb()));
public bool shouldIChangeTheColor { get; set; } = true;
public bool selectedToMove { get; set; } = true;
public bool selectedToLink { get; set; } = true;
}
Usage...
List<PropertiesClass> PropertiesClasses = new List<PropertiesClass>();
PropertiesClass PropertiesClass = new PropertiesClass();
PropertiesClasses.Add(PropertiesClass);
Serialize(PropertiesClasses);
If thats not a homework or study stuff you better use Json.NET to serialize your classes. Reinvent the well is probably gonna cost you more time.