黑马程序员技术交流社区

标题: .NET文件操作 [打印本页]

作者: 380933512    时间: 2012-11-3 23:41
标题: .NET文件操作
文件的建立

源代码:
private void Button1_Click(object sender, System.EventArgs e)
{
//string wenjian;
//wenjian = filename.Text;
if (this.filename.Text.ToString().Trim()=="")
{
this.body.Text = "********";
}
else
{
try
{
string thisfilename=filename.Text.ToString();
FileStream fsMyfile = new FileStream(thisfilename,FileMode.Create,FileAccess.ReadWrite);
fsMyfile.Close();
this.body.Text = "********";
}
catch
{
//Console.WriteLine("{0} Second exception caught.", e);

this.body.Text = "********";

}
}

}

文件的删除


源代码:

private void Button4_Click(object sender, System.EventArgs e)
{
if (this.filename.Text.ToString().Trim()=="")
{
this.body.Text = "********";
}
else
{
try
{
string thisfilename=filename.Text.ToString();

File.Delete(thisfilename);
this.body.Text = "********";

}
catch
{
//Console.WriteLine("{0} Second exception caught.", e);

this.body.Text = "********";

}


}

}
文件的读取

源代码:

private void Button2_Click(object sender, System.EventArgs e)

{
if (this.filename.Text.ToString().Trim()=="")
{
this.body.Text = "请选择文件名称!";
}
else
{
try
{


string thisfilename=filename.Text.ToString();
StreamReader srMyfile = new StreamReader(thisfilename);
srMyfile.BaseStream.Seek(0,SeekOrigin.Begin);
string sl;
sl = srMyfile.ReadToEnd();
this.body.Text = sl;
srMyfile.Close();
}
catch
{
//Console.WriteLine("{0} Second exception caught.", e);

this.body.Text = "此文件不存在!";

}

}

}
文件的写入

源代码:

private void Button3_Click(object sender, System.EventArgs e)
{
if (this.filename.Text.ToString().Trim()=="")
{
this.body.Text = "********";
}
else
{
try
{
string thisfilename=filename.Text.ToString();
StreamWriter swMyfile = new StreamWriter(thisfilename);
string xieru = body.Text.ToString();
swMyfile.WriteLine(xieru);
swMyfile.Flush();
swMyfile.Close();
this.body.Text = "********";

}
catch
{
//Console.WriteLine("{0} Second exception caught.", e);

this.body.Text = "********";

}


}


}







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2