2016-04-02 60 views
1

我正在嘗試製作一個程序,該程序同時顯示用戶輸入並寫入到同一用戶輸入數據的文本文件中的文本。我試過包裹與Task.Run代碼:如何寫入C#文件

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''不能從'字符串'轉換爲'System.IO.Stream'

而當我嘗試沒有任何包裝的普通方式時,我得到一個同步錯誤。任何解決這個問題的方法都將非常感激。

+0

請提供一個MCVE(http://stackoverflow.com/help/mcve)來演示此問題。你的例子引入了不相關的信息(比如'show.Text'和'show2.Text',它們在代碼中沒有用到)。你需要提供一個清楚的例子,說明你正在嘗試做什麼,而沒有所有其他混亂對於手頭的問題毫無意義。 –

+0

驅動器A和B用於軟盤,您需要先更改驅動器 –

+0

我將驅動器A分配給了我的輔助硬盤驅動器。 – Yetoo

回答

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元素。這通常不會在像Windows窗體這樣的單線程UI庫中被允許,因此您需要在將數據發送回後臺線程之前將數據複製出來,否則代碼將失敗,如您所見。

+0

我遇到了一個問題,當創建name.txt的代碼執行時,出現錯誤:訪問路徑'c:\ users \ username \ documents \ visual studio 2015 \ Projects \ normieap \ normieap \ bin \ x86 \ Debug \ AppX \ name.txt'被拒絕。我應該如何解決這個問題? – Yetoo

+0

你將需要提供錯誤。如果完全不同,那麼你可能會寫另一個問題。 – yumaikas