.NET Framework增删移动文件,文件夹目录读取删除

//写入文件

private void btnWriteAll_Click(object sender, EventArgs e)
{

// 创建文件流
FileStream fs = new FileStream(“D:\\myfile.txt”, FileMode.Create);
// 创建写入器
StreamWriter sw = new StreamWriter(fs);
// 以流的方式写入数据
sw.Write(this.txtContent.Text.Trim());
//关闭写入器
sw.Close();
// 关闭文件流
fs.Close();
}
//读取文件
private void btnReadAll_Click(object sender, EventArgs e)
{
//创建文件流
FileStream fs = new FileStream(“D:\\myfile.txt”, FileMode.Open);
//创建读取器
//StreamReader sr = new StreamReader(fs, Encoding.Default); 乱码问题
StreamReader sr = new StreamReader(fs);
//以流的方式读取数据
this.txtContent.Text = sr.ReadToEnd();
//关闭读取器
sr.Close();
//关闭文件流
fs.Close();
}
//模拟写入系统日志
private void btnWriteLine_Click(object sender, EventArgs e)
{
// 创建文件流
FileStream fs = new FileStream(“D:\\myfile.txt”, FileMode.Append);
// 创建写入器
StreamWriter sw = new StreamWriter(fs);
// 以流的方式逐行写入
sw.WriteLine(DateTime.Now.ToString() + “文件操作正常”);
//关闭写入器
sw.Close();
//关闭文件流
fs.Close();
}
//删除文件
private void btnDel_Click(object sender, EventArgs e)
{
File.Delete(this.txtFrom.Text);
}
//复制文件
private void btnCopy_Click(object sender, EventArgs e)
{
if (File.Exists(this.txtTo.Text.Trim()))
{
File.Delete(this.txtTo.Text);
}
File.Copy(this.txtFrom.Text.Trim(), this.txtTo.Text.Trim()); //复制文件
}
//移动文件
private void btnRemove_Click(object sender, EventArgs e)
{
if (File.Exists(this.txtTo.Text.Trim()))
{
File.Delete(this.txtTo.Text);
}
if (File.Exists(this.txtFrom.Text.Trim()))
{
File.Move(this.txtFrom.Text.Trim(), this.txtTo.Text.Trim());
}
else
{
MessageBox.Show(“该文件不存在!”,”提示”, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
}
//获取当前目录下的文件
private void btnShowAllFiles_Click(object sender, EventArgs e)
{
string[] files = Directory.GetFiles(“C:\\myview”);
this.txtContent.Clear();
foreach (string item in files)
{
this.txtContent.Text += item + “\r\n”;
}
}
//获取指定目录下的所有子目录
private void btnShowSubDir_Click(object sender, EventArgs e)
{
string[] dirs = Directory.GetDirectories(“C:\\Drivers”);
this.txtContent.Clear();
foreach (string item in dirs)
{
this.txtContent.Text += item + “\r\n”;
}
}

//创建目录
private void btnCreate_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(“c:\\Myfile\\newfiles”);
}

//删除指定目录下的所有子目录和文件
private void btnDelAllFiles_Click(object sender, EventArgs e)
{
//Directory.Delete(“c:\\Myfile”); //目录不能为空
DirectoryInfo dir = new DirectoryInfo(“C:\\Myfile”);
dir.Delete(true);
}

未经允许不得转载:技术啦 - 关注IT,建站和运维,分享最新教程,资源 » .NET Framework增删移动文件,文件夹目录读取删除

赞 (1) 打赏

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址