简体   繁体   中英

How to write to a file in C#

I am trying to make a program that, at the same time, displays text that the user inputted and writes to a text file of that same user input data. I've tried wrapping the the code with Task.Run:

 private void button_Click(object sender, RoutedEventArgs e)
        {
            show.Text = inputText.Text;
            //Debug.WriteLine(check1_cont.ToString());
            //Debug.WriteLine(check2_cont.ToString());

            if (check1_cont && check2_cont == true )
            {
                show2.Text = inputText.Text;

                Task.Run(() => File.WriteAllText(@"A:\temp\name.txt", inputText.Text));
            }

        } 

But I get an exception error after the second text (the one in the if statement) when I press the button:

An exception of type 'System.Exception' occurred in normieap.exe but
was not handled in user code

Additional information: The application called an interface that was
marshalled for a different thread. (Exception from HRESULT: 0x8001010E
(RPC_E_WRONG_THREAD))

I try using StreamWriter:

private void button_Click(object sender, RoutedEventArgs e)
        {
            show.Text = inputText.Text;
            //Debug.WriteLine(check1_cont.ToString());
            //Debug.WriteLine(check2_cont.ToString());

            if (check1_cont && check2_cont == true )
            {
                show2.Text = inputText.Text;
                using (StreamWriter writer = new StreamWriter(@"A:\temp\name.txt"))
                {
                    writer.WriteLine(inputText.Text);
                }
             }

        } 

But I get an error on the line:

using (StreamWriter writer = new StreamWriter(@"A:\temp\name.txt"))

Because '@"A:\\temp\\name.txt"' cannot convert from 'string' to 'System.IO.Stream'

And when I try just the normal way without any wrappers I get a synchronous error. Any solutions to this problem would be much appreciated.

When you run a task asyncrounously, it isn't guaranteed to run on the UI thread. Take your first example and try this:

private void button_Click(object sender, RoutedEventArgs e)
    {
        show.Text = inputText.Text;
        //Debug.WriteLine(check1_cont.ToString());
        //Debug.WriteLine(check2_cont.ToString());

        if (check1_cont && check2_cont == true )
        {
            show2.Text = inputText.Text;
            // Copy the text to output
            string outputToWrite = inputText.Text;
            // use the copied text
            Task.Run(() => File.WriteAllText(@"A:\temp\name.txt", outputToWrite));
        }

    }

What's going on here is that a background thread is trying to access a GUI element. That's generally not allowed in singled threaded UI libraries like Windows Forms, so you need to copy the data out of the control before sending it back to the background thread, otherwise the code will fail as you have seen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM