您的位置:首页 > 编程语言 > C#

C#学习笔记(十三):读写Txt文件

2006-02-19 14:33 471 查看
.NET内置了两个基本控件来提取用户输入的文本:TextBox和RichTextBox。这两个控件都派生于基类TextBoxBase,而TextBoxBase派生于Control。
TextBoxBase提供了在文本框中处理文本的基本功能,例如选择文本、剪切和从剪切板上粘贴,以及许多事件。
利用TextBox的Validating事件,将同类型输入验证进行代码归类,减少重复代码的编写。例如:姓名和地址两个输入框,验证规则为均不许为空,即可在初始化窗体时用如下代码进行相应验证事件的订阅
this.txtName.Validating += new System.ComponentModel.CancelEventHandler(this.txtBoxEmpty_Validating);
this.txtAddress.Validating += new System.ComponentModel.CancelEventHandler(this.txtBoxEmpty_Validating);

private void txtBoxEmpty_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextBox tb;
tb = (TextBox)sender;
// If the text is empty we set the background color of the
// TextBox to red to indicate a problem. We use the tag value
// of the control to indicate if the control contains valid
// information.
if (tb.Text.Length == 0)
{
tb.BackColor = Color.Red;
tb.Tag = false;
}
else
{
tb.BackColor = System.Drawing.SystemColors.Window;
tb.Tag = true;
}
}

RichTextBox可以对其中的文本内容作一些格式化的显示,例如加粗、斜体、超级链接、居中等。
读取文本内容的小例子:
/// <summary>
/// 打开文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void fbtnOpenFile_Click(object sender, System.EventArgs e)
{
openFileDialog1.ShowDialog();
ftxtFilePath.Text = openFileDialog1.FileName;
}
/// <summary>
/// 读取文件内容
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void fbtnReadContent_Click(object sender, System.EventArgs e)
{
StreamReader sr = new StreamReader(ftxtFilePath.Text);

string input;
do
{
input = sr.ReadLine();
if(input != "")
{
this.frtbFileContent.Text += input + "/r/n";
}
}while(sr.Peek()!=-1);

sr.Close();
}
/// <summary>
/// 保存文件内容
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void fbtnSaveContent_Click(object sender, System.EventArgs e)
{
StreamWriter sw = new StreamWriter(this.ftxtFilePath.Text);
sw.Write(frtbFileContent.Text);
sw.Flush();
sw.Close();
}
其中frtbFileContent控件为一个RichTextBox控件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: