Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save data with a button in C# XAML

I want to program a little local database. I have a form written which has different TextBlocks. After I have entered text into the blocks, I will press a button to save the data to a text file.

So I tried it with the following code:

private void button_Click(object sender, RoutedEventArgs e)
{
    string x = textBox.Text;
    string p = "J:\\test.txt";
    File.WriteAllText(p, x);
}

Now my problem is that everytime VS2015 writes an error back: Synchronous operations should not be performed on the UI thread So I tried this:

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);
    };
}

But this also doesn't work. Can somebody help me?

like image 644
Cyberduck Avatar asked Feb 16 '26 00:02

Cyberduck


1 Answers

Going down the async/await route as you are - I would simply change your choice of File.WriteAllText to a 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);
    }

Give that a go and see if you get different results

You can also follow the suggestion of wrapping with Task.Run and then go back to your original method

    private void button_Click(object sender, RoutedEventArgs e)
    {
        string x = textBox.Text;
        string p = "C:\\test.txt";
        Task.Run(() => File.WriteAllText(p, x));
    }
like image 80
Sean Hosey Avatar answered Feb 18 '26 15:02

Sean Hosey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!