将数据保存到C#中的文件

因此,我目前正在开发一个项目,为Pathfinder角色扮演游戏制作自动角色表,并且不知道如何保存数据。 我想将所有变量的当前值保存到扩展名为.pfcsheet的文件中,稍后再打开。 我已经google了,找不到说明如何做的事情,只是如何保存文本框的内容。 我尝试使用saveFileDialog控件,但它一直给我一个“文件名无效”错误,似乎没有人知道原因。

我刚写了一篇关于将对象数据保存到Binary,XML或Json的博客文章 。 听起来您可能想要使用二进制序列化,但也许您希望在应用程序之外编辑文件,在这种情况下,XML或Json可能会更好。 以下是以各种格式执行此操作的function。 有关详细信息,请参阅我的博文。

二进制

///  /// Writes the given object instance to a binary file. /// Object type (and all child types) must be decorated with the [Serializable] attribute. /// To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; 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(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); } } ///  /// 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(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程序集包含在项目中。

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

您必须包含对Newtonsoft.Json程序集的引用,该程序集可以从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] attribute. ///  /// 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(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(); } } ///  /// 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(string 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(); } } 

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

我想你可能会想要这样的东西

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

查看XMLSerializer类。

如果您想保存对象的状态并且能够在其他时间轻松地重新创建它们,那么序列化是您最好的选择。

序列化它,以便返回完整格式的XML。 使用StreamWriter类将其写入文件。

稍后,您可以读入文件的内容,并将其与要填充的对象的实例一起传递给序列化程序类,并且序列化程序也将负责反序列化。

以下是从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(); } } 

这是一个类似于Sachin的简单示例。 建议在非托管文件资源上使用“using”语句:

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

using Statement(C#参考)

以下是MSDN上有关如何将文本写入文件的指南:

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

我会从那里开始,然后在您继续开发时发布更多,更具体的问题。

从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

一个class轮:

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

如果文件不存在,则创建该文件,如果存在则覆盖该文件。 确保您具有写入该位置的适当权限,否则您将获得exception。

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

将字符串写入文本文件并确保它始终覆盖现有内容。