如何在应用程序启动时使用file.ReadAllText()保存和读取文本文件
本文关键字:保存 读取 文件 取文本 ReadAllText file 应用程序 启动 | 更新日期: 2023-09-27 18:01:10
我在应用程序启动时保存一个文本文件,并从应用程序启动中读取该文本文件。
这不是在应用程序启动时保存我的文件,这段代码有什么问题?
在应用程序启动代码时保存文本文件。
private void Savebutton1_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + "Book.txt", true);
string json = JsonConvert.SerializeObject(vals);
sw.Write(json);
MessageBox.Show("Book Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
从应用程序启动代码加载文本文件。
string path = Path.Combine(Application.StartupPath, "ChequeBook.txt");
string textholder;
try
{
// Use StreamReader to consume the entire text file.
using (StreamReader reader = new StreamReader(path))
{
MessageBox.Show("Reached Here");
textholder = reader.ReadToEnd();
MessageBox.Show("Reached Here - 2");
}
if (textholder == string.Empty) {
return;
}
// Deserialise it from Disk back to a Dictionary
string jsonToRead = File.ReadAllText(textholder);
List<KeyValuePair<int, string>> myDictionaryReconstructed =
JsonConvert.DeserializeObject<List<KeyValuePair<int, string>>>(jsonToRead);
我想保存&使用file.CreateText方法在应用程序文件夹中写入文本文件。
找到第一个答案:
这将写入并保存应用程序文件夹中的文本文件
using (StreamWriter sw = File.CreateText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Book.txt")))
{
string json = JsonConvert.SerializeObject(vals);
sw.Write(json);
}
MessageBox.Show("Book Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
我想从应用程序文件夹中读取文本文件。
这将从应用程序文件夹中读取文本文件的内容
string jsonToRead = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Book.txt"));