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. 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. 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.
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;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.