我想编写一个小型本地数据库。我编写了一个具有不同 TextBlocks 的表单。在 block 中输入文本后,我将按一个按钮将数据保存到文本文件中。
所以我用下面的代码试了一下:
private void button_Click(object sender, RoutedEventArgs e)
{
string x = textBox.Text;
string p = "J:\\test.txt";
File.WriteAllText(p, x);
}
现在我的问题是每次 VS2015 都会写回一个错误: 不应在 UI 线程上执行同步操作 所以我尝试了这个:
private async void button_Click(object sender, RoutedEventArgs e)
{
string x = textBox.Text;
string p = "J:\\test.txt";
await WriteTextAsync(p,x);
}
private async Task WriteTextAsync(string filePath, string text)
{
byte[] encodedText = Encoding.Unicode.GetBytes(text);
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true))
{
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);
};
}
但这也行不通。有人可以帮助我吗?
最佳答案
像你一样沿着异步/等待路线走下去——我只是将你对 File.WriteAllText 的选择更改为 StreamWriter:
private async void button_Click(object sender, RoutedEventArgs e)
{
string x = textBox.Text;
string p = "J:\\test.txt";
using (FileStream fs = new FileStream(p, FileMode.Append))
using (StreamWriter sw = new StreamWriter(fs))
await sw.WriteLineAsync(x);
}
试一试,看看是否会得到不同的结果
您也可以按照建议使用 Task.Run 包装,然后返回到您原来的方法
private void button_Click(object sender, RoutedEventArgs e)
{
string x = textBox.Text;
string p = "C:\\test.txt";
Task.Run(() => File.WriteAllText(p, x));
}
关于c# - 使用 C# XAML 中的按钮保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34815082/