web-dev-qa-db-ja.com

C#でファイルにデータを保存する

したがって、私は現在、パスファインダーロールプレイングゲームの自動化されたキャラクターシートを作成するプロジェクトに取り組んでおり、データの保存方法について途方に暮れています。すべての変数の現在の値を拡張子.pfcsheetのファイルに保存し、後で開きたいのですが。私はググってみましたが、これを行う方法、テキストボックスの内容を保存する方法を説明するものを見つけることができません。 saveFileDialogコントロールを使用しようとしましたが、「ファイル名が無効です」というエラーが表示され続け、誰もその理由を知りません。

8
Excelzn

私は オブジェクトのデータをBinary、XML、またはJsonに保存することに関するブログ投稿 を書いたところです。おそらくバイナリシリアライゼーションを使用したいようですが、おそらくファイルをアプリの外部で編集する必要があります。その場合、XMLまたはJsonの方が優れている可能性があります。さまざまな形式でこれを行う関数を次に示します。詳細については、私のブログ投稿を参照してください。

バイナリ

/// <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

System.Xmlアセンブリがプロジェクトに含まれている必要があります。

/// <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.NET NuGet Package から取得できるNewtonsoft.Jsonアセンブリへの参照を含める必要があります。

/// <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();
    }
}

// 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");
21
deadlydog

このようなものが欲しくなるかもしれません

// 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();
15
Sachin Kainth

以下は、Sachinに似た簡単な例です。アンマネージファイルリソースで "using"ステートメントを使用することをお勧めします。

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

singステートメント(C#リファレンス)

3
BryanJ

XMLSerializer クラスを調べます。

オブジェクトの状態を保存して、後で簡単に再作成できるようにしたい場合は、シリアル化が最適です。

完全な形式のXMLが返されるようにシリアル化します。 StreamWriterクラスを使用して、これをファイルに書き込みます。

後で、ファイルの内容を読み込んで、入力するオブジェクトのインスタンスとともにシリアライザクラスに渡すことができます。シリアライザは、逆シリアル化も処理します。

Microsoft Support から抜粋したコードスニペットを次に示します。

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

ファイルにテキストを書き込む方法に関するガイドに関するMSDNの記事は次のとおりです。

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

私はそこから始めて、開発を続けながら、追加のより具体的な質問を投稿します。

2
Nick Heidke

System.IO名前空間(特にFileオブジェクトまたはFileInfoオブジェクト)から始めれば、すぐに始めることができます。

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

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

0
Keith

一発ギャグ:

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

ファイルが存在しない場合は作成し、存在する場合は上書きします。その場所に書き込むための適切な権限があることを確認してください。そうしないと、例外が発生します。

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

文字列をテキストファイルに書き込み、常に既存のコンテンツを上書きすることを確認してください。

0
Ogglas