如何用C#写入文件

时间:2016-04-02 04:20:02

标签: c#

我正在尝试制作一个程序,同时显示用户输入的文本并写入相同用户输入数据的文本文件。我尝试用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));
            }

        } 

但是当我按下按钮时,我在第二个文本(if语句中的那个)之后出现异常错误:

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

我尝试使用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);
                }
             }

        } 

但我收到错误:

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

因为'@“A:\ temp \ name.txt”'无法从'string'转换为'System.IO.Stream'

当我尝试没有任何包装器的正常方式时,我得到一个同步错误。对此问题的任何解决方案都将非常感激。

1 个答案:

答案 0 :(得分:1)

当您异步运行任务时,不保证在UI线程上运行。拿你的第一个例子来试试这个:

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

    }

这里发生的是后台线程正在尝试访问GUI元素。这通常不允许在单个线程UI库(如Windows窗体)中使用,因此您需要将数据从控件中复制出来,然后再将其发送回后台线程,否则代码将会失败,如您所见。