[英]How to write to a file in 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'
當我在沒有任何包裝器的情況下嘗試正常方式時,我會收到同步錯誤。 對此問題的任何解決方案將不勝感激。
當您異步運行任務時,不能保證它在 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 庫中通常是不允許的,因此您需要在將數據發送回后台線程之前將數據從控件中復制出來,否則代碼將失敗,如您所見。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.