Enregistrement de données dans un fichier en C #

Je travaille donc actuellement sur un projet visant à créer une feuille de personnage automatisée pour le jeu de rôle Pathfinder, et je ne sais pas comment sauvegarder les données. Je veux enregistrer la valeur actuelle de toutes mes variables dans un fichier portant l’extension .pfcsheet et l’ouvrir plus tard. J’ai cherché sur Google et je ne trouve pas quelque chose qui explique comment faire cela, mais comment enregistrer le contenu d’une zone de texte. J’ai essayé d’utiliser le contrôle saveFileDialog mais il continue à me donner l’erreur “Le nom de fichier n’est pas valide” et personne ne semble savoir pourquoi.

Je viens d’écrire un article sur la sauvegarde des données d’un object au format binary, XML ou Json . Il semble que vous souhaitiez probablement utiliser la sérialisation binary, mais vous souhaitez peut-être que les fichiers soient modifiés en dehors de votre application, auquel cas XML ou Json pourrait être préférable. Voici les fonctions pour le faire dans les différents formats. Voir mon blog pour plus de détails.

Binaire

///  /// Writes the given object instance to a binary file. /// Object type (and all child types) must be decorated with the [Serializable] atsortingbute. /// To prevent a variable from being serialized, decorate it with the [NonSerialized] atsortingbute; cannot be applied to properties. ///  /// The type of object being written to the XML file. /// The file path to write the object instance to. /// The object instance to write to the XML file. /// If false the file will be overwritten if it already exists. If true the contents will be appended to the file. public static void WriteToBinaryFile(ssortingng filePath, T objectToWrite, bool append = false) { using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create)) { var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binaryFormatter.Serialize(stream, objectToWrite); } } ///  /// Reads an object instance from a binary file. ///  /// The type of object to read from the XML. /// The file path to read the object instance from. /// Returns a new instance of the object read from the binary file. public static T ReadFromBinaryFile(ssortingng filePath) { using (Stream stream = File.Open(filePath, FileMode.Open)) { var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); return (T)binaryFormatter.Deserialize(stream); } } 

XML

Nécessite l’assembly System.Xml à inclure dans votre projet.

 ///  /// Writes the given object instance to an XML file. /// Only Public properties and variables will be written to the file. These can be any type though, even other classes. /// If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] atsortingbute. /// Object type must have a parameterless constructor. ///  /// The type of object being written to the file. /// The file path to write the object instance to. /// The object instance to write to the file. /// If false the file will be overwritten if it already exists. If true the contents will be appended to the file. public static void WriteToXmlFile(ssortingng filePath, T objectToWrite, bool append = false) where T : new() { TextWriter writer = null; try { var serializer = new XmlSerializer(typeof(T)); writer = new StreamWriter(filePath, append); serializer.Serialize(writer, objectToWrite); } finally { if (writer != null) writer.Close(); } } ///  /// Reads an object instance from an XML file. /// Object type must have a parameterless constructor. ///  /// The type of object to read from the file. /// The file path to read the object instance from. /// Returns a new instance of the object read from the XML file. public static T ReadFromXmlFile(ssortingng filePath) where T : new() { TextReader reader = null; try { var serializer = new XmlSerializer(typeof(T)); reader = new StreamReader(filePath); return (T)serializer.Deserialize(reader); } finally { if (reader != null) reader.Close(); } } 

Json

Vous devez inclure une référence à l’assembly Newtonsoft.Json, qui peut être obtenue à partir du package Json.NET NuGet .

 ///  /// Writes the given object instance to a Json file. /// Object type must have a parameterless constructor. /// Only Public properties and variables will be written to the file. These can be any type though, even other classes. /// If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] atsortingbute. ///  /// The type of object being written to the file. /// The file path to write the object instance to. /// The object instance to write to the file. /// If false the file will be overwritten if it already exists. If true the contents will be appended to the file. public static void WriteToJsonFile(ssortingng filePath, T objectToWrite, bool append = false) where T : new() { TextWriter writer = null; try { var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite); writer = new StreamWriter(filePath, append); writer.Write(contentsToWriteToFile); } finally { if (writer != null) writer.Close(); } } ///  /// Reads an object instance from an Json file. /// Object type must have a parameterless constructor. ///  /// The type of object to read from the file. /// The file path to read the object instance from. /// Returns a new instance of the object read from the Json file. public static T ReadFromJsonFile(ssortingng filePath) where T : new() { TextReader reader = null; try { reader = new StreamReader(filePath); var fileContents = reader.ReadToEnd(); return JsonConvert.DeserializeObject(fileContents); } finally { if (reader != null) reader.Close(); } } 

Exemple

 // To save the characterSheet variable contents to a file. WriteToBinaryFile("C:\CharacterSheet.pfcsheet", characterSheet); // To load the file contents back into a variable. CharacterSheet characterSheet = ReadFromBinaryFile("C:\CharacterSheet.pfcsheet"); 

Je pense que vous pourriez vouloir quelque chose comme ça

 // Compose a ssortingng that consists of three lines. ssortingng lines = "First line.\r\nSecond line.\r\nThird line."; // Write the ssortingng to a file. System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt"); file.WriteLine(lines); file.Close(); 

Regardez dans la classe XMLSerializer .

Si vous souhaitez enregistrer l’état des objects et pouvoir les recréer facilement à un autre moment, la sérialisation est votre meilleur pari.

Sérialisez-le de manière à obtenir le code XML entièrement formé. Ecrivez ceci dans un fichier en utilisant la classe StreamWriter .

Plus tard, vous pourrez lire le contenu de votre fichier et le transmettre à la classe de sérialiseur avec une instance de l’object que vous souhaitez renseigner. Le sérialiseur se chargera également de la désérialisation.

Voici un extrait de code provenant du support technique de Microsoft :

 using System; public class clsPerson { public ssortingng FirstName; public ssortingng MI; public ssortingng LastName; } class class1 { static void Main(ssortingng[] args) { clsPerson p=new clsPerson(); p.FirstName = "Jeff"; p.MI = "A"; p.LastName = "Price"; System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType()); // at this step, instead of passing Console.Out, you can pass in a // Streamwriter to write the contents to a file of your choosing. x.Serialize(Console.Out, p); Console.WriteLine(); Console.ReadLine(); } } 

Voici un exemple simple similaire à celui de Sachin. Il est recommandé d’utiliser une instruction “using” sur la ressource de fichier non gérée:

  // using System.IO; ssortingng filepath = @"C:\test.txt"; using (StreamWriter writer = new StreamWriter(filepath)) { writer.WriteLine("some text"); } 

using statement (référence C #)

Voici un article de MSDN sur un guide expliquant comment écrire du texte dans un fichier:

http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

Je commencerais par là, puis poserais d’autres questions plus spécifiques au fur et à mesure que vous poursuivez votre développement.

Commencer par l’espace de noms System.IO (en particulier les objects File ou FileInfo) devrait vous aider à démarrer.

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx

Bon mot:

 System.IO.File.WriteAllText(@"D:\file.txt", content); 

Il crée le fichier s’il n’existe pas et le remplace s’il existe. Assurez-vous que vous disposez des privilèges appropriés pour écrire sur l’emplacement, sinon vous obtiendrez une exception.

https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Écrivez une chaîne dans un fichier texte et assurez-vous qu’il écrase toujours le contenu existant.