我想编程一个小本地数据库。我有一个写有不同TextBlocks的表单。在块中输入文本后,我将按下按钮将数据保存到文本文件中。用C#XAML中的按钮保存数据
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);
};
}
但这也行不通。有人能帮助我吗?
你正在为什么样的应用程序工作? WPF? UWP? – chameleon86
“也不行”很含糊。当您使用第二组发布代码时会发生什么? – Tim
也许有帮助http://stackoverflow.com/questions/31769505/ccreating-a-file-with-filestream-returns-an-invalidoperationexception – kenny