实现功能:编辑文件
用到的命名空间:
System //这个不用解释了吧
System.IO //系统的各种流(stream)
System.Windows.Forms //winform
System.Drawing //绘图
读文件用System.IO下的StreamReader,写文件用StreamWrtier
实现流程
先用winform做一个界面:
class Form1:Form{
public Form1(){
inittext();
}
public TextBox t = new TextBox();
public TextBox t2 = new TextBox();
public Button b = new Button();
public Button b2 = new Button();
public void inittext(){
t.Text = "text";
t.Multiline = true;
t.ScrollBars = ScrollBars.Vertical;
t.Size = new Size(400,500);
Controls.Add(t);
t2.Text = "请输入文件名";
t2.Top = 0;
t2.Left = 401;
Controls.Add(t2);
b.Top = 20;
b.Left = 401;
b.Text = "提交文件名";
b.Click += btnclick;
Controls.Add(b);
b2.Top = 40;
b2.Left = 401;
b2.Size = new Size(100,20);
b2.Text = "提交文件内容";
b2.Click += btnclick2;
Controls.Add(b2);
}
class m{
static void Main(){
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 f = new Form1();
f.Size = new Size(600,600);
f.Text = "记事本";
Application.Run(f);
}
判断文件名是否为空,如果不是,判断是否有此文件,有则将t设置为文件内容,没有则新建
public void btnclick(object sender,EventArgs e){
if(t2.Text != ""){
if(File.Exists(t2.Text)){
StreamReader sr = new StreamReader(t2.Text);
if(sr != null){
string s = sr.ReadLine();
string context = "";
while(s != null){
context += s;
s = sr.ReadLine();
}
t.Text = context;
sr.Close();
}
}else{
StreamWriter sr = new StreamWriter(t2.Text);
sr.Close();
}
}
}
提交文件内容,写入
public void btnclick2(object sender,EventArgs e){
StreamWriter sr = new StreamWriter(t2.Text);
char[] c = t.Text.ToCharArray();
sr.Write(c);
sr.Close();
}