web-dev-qa-db-fra.com

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.

6
Excelzn

Je viens d'écrire un article de blog sur la sauvegarde des données d'un objet au format binaire, XML ou Json . Il semble que vous souhaitiez probablement utiliser la sérialisation binaire, mais peut-être souhaitez-vous 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

/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the XML file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the XML file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string 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);
    }
}

/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the XML.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string 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 pour être inclus dans votre projet.

/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string 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();
    }
}

/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string 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 à Newtonsoft.Json Assembly, qui peut être obtenue à partir du package Json.NET NuGet Package .

/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string 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();
    }
}

/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
    TextReader reader = null;
    try
    {
        reader = new StreamReader(filePath);
        var fileContents = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<T>(fileContents);
    }
    finally
    {
        if (reader != null)
            reader.Close();
    }
}

Exemple

// To save the characterSheet variable contents to a file.
WriteToBinaryFile<CharacterSheet>("C:\CharacterSheet.pfcsheet", characterSheet);

// To load the file contents back into a variable.
CharacterSheet characterSheet = ReadFromBinaryFile<CharacterSheet>("C:\CharacterSheet.pfcsheet");
19
deadlydog

Je pense que vous voudrez peut-être quelque chose comme ça

// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();
14
Sachin Kainth

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;
        string filepath = @"C:\test.txt";
        using (StreamWriter writer = new StreamWriter(filepath))
        {
            writer.WriteLine("some text");
        }

using statement (référence C #)

3
BryanJ

Regardez dans XMLSerializer class.

Si vous souhaitez enregistrer l'état des objets 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'objet que vous souhaitez renseigner. Le sérialiseur se chargera également de la désérialisation.

Voici un extrait de code extrait de Support technique Microsoft :

using System;

public class clsPerson
{
  public  string FirstName;
  public  string MI;
  public  string LastName;
}

class class1
{ 
   static void Main(string[] 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();
   }
} 
3
xbonez

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.

2
Nick Heidke

Commencer par l'espace de noms System.IO (en particulier les objets 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

0
Keith

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.

0
Ogglas