Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用C#XAML中的按钮保存数据_C#_Xaml_Visual Studio 2015 - Fatal编程技术网

用C#XAML中的按钮保存数据

用C#XAML中的按钮保存数据,c#,xaml,visual-studio-2015,C#,Xaml,Visual Studio 2015,我想编一个本地数据库。我写了一个有不同文本块的表单。在我将文本输入到块中后,我将按下按钮将数据保存到文本文件中 因此,我尝试了以下代码: private void button_Click(object sender, RoutedEventArgs e) { string x = textBox.Text; string p = "J:\\test.txt"; File.WriteAllText(p, x); } 现在我的问题是每次VS2015都会写回一个错误: 不应

我想编一个本地数据库。我写了一个有不同文本块的表单。在我将文本输入到块中后,我将按下按钮将数据保存到文本文件中

因此,我尝试了以下代码:

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.writealText更改为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));
    }

你在为哪种应用程序工作?WPF?UWP?“也不起作用”是非常模糊的。当您使用第二组发布的代码时会发生什么情况?可能会有帮助您正在为哪种类型的应用程序工作?WPF?UWP?:我在UWP上工作“也不工作”是非常模糊的。使用第二组发布的代码时会发生什么情况?:出现相同的故障。不应在UI线程上执行同步操作。考虑在Task.Run.thx中包装此方法以进行快速回复,但现在我还有另一个问题:它不可能将“字符串”转换成“Stry.IO .String”。我已经编辑了我的答案给FieldScript编写文件,而不是字符串路径。将FileMode更改为适合您需要的模式。同样的失败:不应在UI线程上执行同步操作。考虑在任务.Run中包装这个方法。我已经更新了包括如何包装任务。按建议运行。现在出现另一个错误:一个接口,它是由程序调用的另一个线程。(HRESULT的例外:0x8001010E(RPC_E_错误的_线程))我很抱歉回答这么多问题。