C#文件操作知识点(2)
Flile类的常用方法
序号
方法
说明
1
Exists(stringPath)
用于检查指定文件是否存在,该方法返回一个布尔值
2
Copy(stringSourceFilePath,stringDestinationFilePath)
将指定路径的源文件中的内容复制到目标文件中,如果目标文件不存在,则在指定路径中新建一个文件
3
Move(stringsourceFileName,stringdestFileName)
将指定文件移到一个新的路径
4
Delete(stringpath)
删除指定的文件,如果指定的文件不存在,则不引发异常
Directory类的常用方法
序号
方法
说明
1
Exists(stringpath)
用于坚持指定的文件夹在磁盘上是否存在
2
Move(stringsourceDirName,stringDestDirName)
用于将文件或目录及其内容移到新位置
3
Delete(string,bool)
删除指定目录,如果bool值为true,则删除子目录中的所有目录内容
例:
代码:
privatevoidbutton1_Click(objectsender,EventArgse)
{
openFileDialog1.Filter="全部文件*.*|*.*";
openFileDialog1.FileName="全部文件";
openFileDialog1.ShowDialog();
this.textBox1.Text=openFileDialog1.FileName;
}
privatevoidbutton2_Click(objectsender,EventArgse)
{
openFileDialog1.Filter="全部文件*.*|*.*";
openFileDialog1.FileName="全部文件";
openFileDialog1.ShowDialog();
this.textBox2.Text=openFileDialog1.FileName;
}
//复制文件
privatevoidbutton3_Click(objectsender,EventArgse)
{
if(!File.Exists(this.textBox1.Text))
{
MessageBox.Show("文件不存在");
}
else
{
File.Copy(this.textBox1.Text,this.textBox2.Text);
MessageBox.Show("拷贝成功");
}
}
//移动文件
privatevoidbutton4_Click(objectsender,EventArgse)
{
if(!File.Exists(this.textBox1.Text))
{
MessageBox.Show("文件不存在");
}
else
{
File.Move(this.textBox1.Text,this.textBox2.Text);
MessageBox.Show("移动成功");
}
}
//删除文件
privatevoidbutton5_Click(objectsender,EventArgse)
{
if(!File.Exists(this.textBox1.Text))
{
MessageBox.Show("文件不存在");
}
else
{
File.Delete(this.textBox1.Text);
MessageBox.Show("删除成功");
}
}
2.FileInfo类和DirectoryInfo类FileInfo类的属性和方法
属性
说明
Exists
用于检查指定文件是否存在,返回一个bool值
Extension
获取表示文件扩展命名部分的字符串
Name
获取文件名
FullName
获取目录或文件的完整目录
方法
说明
CopyTo(string)
将现有文件复制到新文件,不允许覆盖现有文件
Delete()
永久删除文件
MoveTo(string)
将指定文件移到新位置(string)
例:
DirectoryInfodi=newDirectoryInfo("D:\testDir");
//返回当前目录的子目录
DirectoryInfo[]subDir=di.GetDirectories();
//返回当前目录的文件列表
FileInfo[]fi=di.GetFiles();
序列化与反序列化步骤:
1.引入命名空间:usingSystem.Runtime.Serialization.Formatters.Binary;
2.在SavingInfo、Remind等类的头部加一个标记[Serializable],例如:
[Serializable]
PublicclassSavingInfo
{
//..............
}
3.编写Save()方法和Load()方法,例如:
//序列化方法
publicvoidSave()
{
//定义文件流
FileStreamfs=newFileStream(@"files\save.bin",FileMode.Create);
//二进制方式
BinaryFormatterbf=newBinaryFormatter();
//序列化存储对象
bf.Serialize(this.listArrays);
//关闭文件流
fs.Close();
}
//反序列化方法
publicvoidLoad()
{
//省略判断文件是否存在
FileStreamfs=newFileStream(@"files\save.bin",FileMode.Open);
BinaryFormatterbf=newBinaryFormatter();
//反序列化
this.lisArrays=(SavingInfo)bf.Deserialize(fs);
fs.Close();
}
注:Deserialize()方法将存储介质的数据文件流转换为object类型。
不想序列化的属性在其头部加上[NonSerialized]标记即可。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。