Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将列表中的数据保存到文本文件_C#_List_Text Files - Fatal编程技术网

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

C# 将列表中的数据保存到文本文件,c#,list,text-files,C#,List,Text Files,我正在用这个库录制一个宏。 我想知道如何将“事件”保存在文本文件中,以便以后加载它们 因此,以下是列表: List<MacroEvent> events = new List<MacroEvent>(); List events=new List(); 将数据放入文本文件需要做什么?如果MacroEvent有可用的ToString()方法,您只需迭代列表并打印到文本文件中即可。我建议使用扩展方法。我对MacroEvent一无所知,也不打算从code项目下载代码只是为了

我正在用这个库录制一个宏。 我想知道如何将“事件”保存在文本文件中,以便以后加载它们

因此,以下是列表:

List<MacroEvent> events = new List<MacroEvent>();
List events=new List();

将数据放入文本文件需要做什么?

如果
MacroEvent
有可用的
ToString()
方法,您只需迭代列表并打印到文本文件中即可。

我建议使用扩展方法。我对
MacroEvent
一无所知,也不打算从code项目下载代码只是为了看一看,但下面是它可能的样子

TextWriter tw = new StreamWriter("myFile.txt");
foreach (MacroEvent item in events)
{
    tw.WriteLine(item.ToString());   
}
tw.Close();
public static class MacroEventExtensions
{
    public static void WriteToFile(this List<MacroEvent> events, string path)
    {
        StringBuilder fileContents = new StringBuilder();
        foreach (var e in events)
        {
            fileContents.AppendLine("{0}::{1}",
                [some event id from the object],
                [some event message from the object]);
        }

        File.WriteAllText(path, fileContents.ToString());
    }
}
您有3种选择:

  • 使用ToString()方法将宏事件导出为格式化文本。您可能需要覆盖默认实现。一定要把你需要的所有信息都放进去,否则你以后就无法检索它们了。然后需要读取和解析文件来加载数据

  • 使用内置的.net XML序列化功能。写/读操作非常简单

  • 如果您不打算在另一个应用程序上使用数据,为什么不使用BinarySerializer呢?到目前为止,这是最好的方法,但生成的文件不会是文本格式


  • 我已经尝试过类似的东西,但它不起作用。我在文本文件中只得到“GlobalMacroRecorder.MacroEvent”。无论如何,谢谢你的回答:)BinarySerializer是完美的。谢谢
    events.WriteToFile([some path])