2016-01-15 13 views
2

我想编程一个小本地数据库。我有一个写有不同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); 
    }; 
} 

但这也行不通。有人能帮助我吗?

+1

你正在为什么样的应用程序工作? WPF? UWP? – chameleon86

+2

“也不行”很含糊。当您使用第二组发布代码时会发生什么? – Tim

+0

也许有帮助http://stackoverflow.com/questions/31769505/ccreating-a-file-with-filestream-returns-an-invalidoperationexception – kenny

回答

1

下乡异步/ AWAIT路线,你是 - 我只想你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)); 
    } 
+0

Thx为您的快速回复,但现在我有另一个问题: 它不可能将“字符串”转换为“System.IO.Stream” –

+0

我已编辑我的答案喂给StreamWriter一个FileStream而不是字符串路径。将FileMode更改为适合您需求的模式。 –

+0

再次发生同样的故障: 不应在UI线程上执行同步操作。考虑在Task.Run中封装这个方法。 –