2010-07-18 31 views
0

有人可以告訴我如何; 使用文本框(s)並將其中的信息寫入文件並從文件(.txt文件)中讀回它們使用文本框並寫入文件並從文件中讀回

謝謝。

PS:我想寫在文本框中一些文本(的WinForms),當我點擊按鈕來保存所有textboxs所有文本寫入文件

丹尼爾

+0

你需要澄清一下:什麼類型的文本框(winforms,asp.net,wpf,silverligh等)和b:你想用它做什麼*。或者更好:你有什麼嘗試?你卡在哪裏?什麼不工作? – 2010-07-18 08:18:56

+0

我想寫一些文本在文本框(也winforms),當我點擊按鈕保存所有文本框中的所有文本寫入文件。 :) – Daniel 2010-07-18 08:51:01

回答

3

這是相當模糊,但string txt = File.ReadAllText(path);File.WriteAllText(path,txt);應處理文件部分(適用於中等大小的文件)。

1

TextBox的.Text屬性包含文本框內的文本。您可以根據需要獲取或設置此屬性以獲取或更改TextBox內的文本。查看File.WriteAllText和File.ReadAllText以讀取/寫入文件中的文本。

0

寫:

FileStream fs = new FileStream("test.txt", FileMode.OpenOrCreate); 
     StreamWriter sw = new StreamWriter(fs); 
     sw.WriteLine(txtTest.Text); 
     sw.Close(); 

閱讀:

FileStream fs = new FileStream("test.txt", FileMode.OpenOrCreate); 
     StreamReader sr = new StreamReader(fs); 
     string myText = string.Empty; 
     while (!sr.EndOfStream) 
     { 
      myText += sr.ReadLine(); 
     } 
     sr.Close(); 
     txtTest.Text = myText; 

這是你問什麼?

+0

不,因爲我知道如何寫或從文件中讀取,但我不知道的是我不知道如何將textBox1.text或其他文本框傳遞給我在另一個類中的方法,在我的節目上。 tnx :) – Daniel 2010-07-18 13:07:20

0

我得到了我想要的這裏是(只寫)代碼:

public partial class Form1 : Form 
{ 
    FileProcess fileprocess; 
    public Form1() 
    { 
     InitializeComponent(); 
     fileprocess = new FileProcess(); 
    } 

    public void writeFile() 
    {   
     fileprocess.writeFile(textBox1.Text,textBox2.Text); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     writeFile(); 
    } 

} 

我的類與文件工作:

class FileProcess 
{ 
    string path = @"c:\PhoneBook\PhoneBook.txt"; 

    public void writeFile(string text1,string text2) 
    { 
     using (StreamWriter sw = new StreamWriter(path,true)) 
     { 
      sw.WriteLine(text1); 
      sw.WriteLine(text2); 
     } 
    } 
} 

我的錯誤是,我試圖來存儲所有textBox轉換爲像「info」這樣的字符串,並通過WriteFile()方法傳遞給它,這就是我陷入它的地方。

tnx全部。

相關問題