在 C# 中将数据保存到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10337410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving data to a file in C#
提问by Excelzn
So i am currently working on a project to make an automated Character Sheet for the Pathfinder Roleplaying Game, and am at a loss as to how to save the data. I want to save the current value of all my variables to a file with the extension .pfcsheet and open it later. I've googled around and can not find something that says how to do this, just how to save the contents of a text box. I tried using the saveFileDialog control but it keeps giving me a "file name is not valid" error and nobody seems to know why.
因此,我目前正在开展一个项目,为探路者角色扮演游戏制作自动角色表,但不知道如何保存数据。我想将所有变量的当前值保存到扩展名为 .pfcsheet 的文件中,稍后再打开。我已经用谷歌搜索了,找不到说明如何执行此操作的内容,只是如何保存文本框的内容。我尝试使用 saveFileDialog 控件,但它一直给我一个“文件名无效”的错误,似乎没有人知道为什么。
采纳答案by deadlydog
I just wrote a blog post on saving an object's data to Binary, XML, or Json. It sounds like you probably want to use Binary serialization, but perhaps you want the files to be edited outside of your app, in which case XML or Json might be better. Here are the functions to do it in the various formats. See my blog post for more details.
我刚刚写了一篇关于将对象数据保存为 Binary、XML 或 Json 的博客文章。听起来您可能想使用二进制序列化,但也许您希望在应用程序之外编辑文件,在这种情况下 XML 或 Json 可能更好。以下是以各种格式执行此操作的函数。有关更多详细信息,请参阅我的博客文章。
Binary
二进制
/// <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
XML
Requires the System.Xml assembly to be included in your project.
需要将 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
杰森
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
您必须包含对 Newtonsoft.Json 程序集的引用,该程序集可以从Json.NET NuGet 包中获得。
/// <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();
}
}
Example
例子
// 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");
回答by Sachin Kainth
I think you might want something like this
我想你可能想要这样的东西
// 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();
回答by Keith
Starting with the System.IO namespace (particularly the File or FileInfo objects) should get you started.
从 System.IO 命名空间(特别是 File 或 FileInfo 对象)开始应该会让你开始。
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx
回答by Nick Heidke
Here's an article from MSDN on a guide for how to write text to a file:
这是 MSDN 上有关如何将文本写入文件的指南的文章:
http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
I'd start there, then post additional, more specific questions as you continue your development.
我会从那里开始,然后在您继续开发时发布其他更具体的问题。
回答by xbonez
Look into the XMLSerializerclass.
进XMLSerializer班看看。
If you want to save the state of objects and be able to recreate them easily at another time, serialization is your best bet.
如果您想保存对象的状态并能够在其他时间轻松地重新创建它们,序列化是您最好的选择。
Serialize it so you are returned the fully-formed XML. Write this to a file using the StreamWriterclass.
对其进行序列化,以便返回完整格式的 XML。使用StreamWriter该类将其写入文件。
Later, you can read in the contents of your file, and pass it to the serializer class along with an instance of the object you want to populate, and the serializer will take care of deserializing as well.
稍后,您可以读入文件的内容,并将其与要填充的对象的实例一起传递给序列化器类,序列化器也将负责反序列化。
Here's a code snippet taken from Microsoft Support:
这是从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();
}
}
回答by BryanJ
Here is a simple example similar to Sachin's. It's recommended to use a "using" statement on the unmanaged file resource:
这是一个类似于 Sachin 的简单示例。建议对非托管文件资源使用“using”语句:
// using System.IO;
string filepath = @"C:\test.txt";
using (StreamWriter writer = new StreamWriter(filepath))
{
writer.WriteLine("some text");
}
回答by Ogglas
One liner:
一个班轮:
System.IO.File.WriteAllText(@"D:\file.txt", content);
It creates the file if it doesn't exist and overwrites it if it exists. Make sure you have appropriate privileges to write to the location, otherwise you will get an exception.
如果文件不存在,则创建该文件,如果存在则覆盖它。确保您具有写入该位置的适当权限,否则您将收到异常。
https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Write string to text file and ensure it always overwrites the existing content.

