【实验目的】
1.理解文件和流概念。
2.熟悉文件操作的方法。
3.掌握Fileatream类使用方法。
4.掌握StreamReader和StreamWriter使用方法。
5.掌握BinaryReader和BinaryWriter使用方法。
【实验内容】
以下5道实验题目最终效果,大家可运行“可执行文件”目录中各题。
1.分别利用File类和FileInfo类、Directory类和DirectoryInfo类实现文件和目录的创建、删除、复制、移动等操作。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace shiyan8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "文件和目录操作实验";
}
private void Form1_Load(object sender, EventArgs e)
{
this.label1.Text = "分别利用File类和FileInfo类、Directory类和DirectoryInfo类实现文件和目录的创建、删除、复制、移动等操作";
this.label1.ForeColor = Color.Green;
this.button1.Text = "File类操作";
this.button2.Text = "FileInfo类操作";
this.button3.Text = "Directory类操作";
this.button4.Text = "DirectoryInfo类操作";
this.button5.Text = "结束";
}
private void button1_Click(object sender, EventArgs e)
{
StreamWriter sw = File.CreateText("c:\\abc.txt");
StreamReader sr = File.OpenText("c:\\abc.txt");
bool isFileExist = File.Exists("c:\\abc.txt");
File.Copy("c:\\abc.txt", "d:\\abc.txt", true);
File.Move("c:\\abc.txt", "d:\\abc.txt");
if (File.Exists("c:\\abc.txt"))
{
File.Delete("C:\\abc.txt");
}
}
private void button2_Click(object sender, EventArgs e)
{
FileInfo f = new FileInfo("c:\\abc.txt");
if (!f.Exists)
{
f.CreateText();
}
StreamWriter sw = f.AppendText();
sw.Write("增加一行数据");
sw.Dispose();
if (f.Exists)
{
f.CopyTo("d:\\abc.txt", true);
}
if (f.Exists)
{
f.Delete();
}
string name = f.Name;
long len = f.Length;
string text = f.Extension;
}
private void button3_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(