[英]How to save data from WPF application to file?
I'm building a WPF application with Visual Studio in which I need to save data from the application to file when closing it and when I open the application, it load the data from the file to continue working.我正在使用 Visual Studio 构建 WPF 应用程序,其中我需要在关闭应用程序时将数据从应用程序保存到文件,当我打开应用程序时,它会从文件加载数据以继续工作。 What type of file do I need to use and how to read/write the file?
我需要使用什么类型的文件以及如何读/写文件?
In school, I know that in C++ you can read from .INP file and write on .OUT file but I guess that's not the case here.在学校,我知道在 C++ 中你可以读取 .INP 文件并写入 .OUT 文件,但我想这里不是这种情况。 I think I could save data as text to a .txt file and convert the data to its original type but this way seems to be inefficient.
我想我可以将数据作为文本保存到 .txt 文件并将数据转换为其原始类型,但这种方式似乎效率低下。
It would be better if I can read and write to the same file.如果我可以读写同一个文件会更好。
Here's a little sample code.这是一个小示例代码。 You can use any file extension you want
您可以使用任何您想要的文件扩展名
//Allows you to perform file IO:
using System.IO;
using System.Windows;
namespace TryStuff2019 {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void BtnSaveToFile_Click(object sender, RoutedEventArgs e) {
var saveThisToFile = "This is some sample text to save";
var fileName = "MyOutput.txt";
//This will save some text to a file in the same folder as your project exe file
using(StreamWriter sw = File.CreateText(fileName)) {
sw.Write(saveThisToFile);
}
}
private void BtnReadFromFile_Click(object sender, RoutedEventArgs e) {
var inputFileName = "MyOutput.txt";
string fileContents;
using(StreamReader sr = File.OpenText(inputFileName)) {
fileContents = sr.ReadToEnd();
}
txtData.Text = fileContents;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.