最近重新学习了C#,将零碎的知识系统化。
今天学习了文件操作的知识——将各种功能集成到一个样例程序里面。
工程链接:http://pan.baidu.com/s/1sjr82Ah
全部代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//额外引入命名空间
using System.IO;
using System.IO.MemoryMappedFiles;
using System.IO.IsolatedStorage;
namespace FileOperater
{
public partial class Window : Form
{
public Window()
{
InitializeComponent();
}
//创建目录
private void createDirectory_Click(object sender, EventArgs e)
{
//有效性检查
if(string.IsNullOrWhiteSpace(directoryPath.Text))
{
MessageBox.Show("请输入有效的目录!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
}
string path = directoryPath.Text;
//方法一:Directory静态类
if(Directory.Exists(path+"I"))
Directory.Delete(path+"I");
Directory.CreateDirectory(path+"I");
//方法二:DirectoryInfo类(比Directory更丰富)
DirectoryInfo di = new DirectoryInfo(path+"II");
if (di.Exists)
di.Delete(true);
di.Create();
MessageBox.Show("目录创建完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//删除目录仿造上面的函数
private void deleteDirectory_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(directoryPath.Text))
{
MessageBox.Show("请输入有效的目录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string path = directoryPath.Text;
if (Directory.Exists(path))
{
Directory.Delete(path);
MessageBox.Show("目录删除完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("指定的目录不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//创建文件
private void createFile_Click(object sender, EventArgs e)
{
//类似Directory操作,同样有两种方法处理
//方法一:File静态类
//有效性检查
if (string.IsNullOrWhiteSpace(filePath.Text))
{
MessageBox.Show("请输入有效的目录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string pathI = filePath.Text+"I";
string pathII = filePath.Text + "II";
if (File.Exists(pathI))
File.Delete(pathI);
try
{
using(var fs= File.Create(pathI))
{
//必须主动释放 否则匿名流将占用文件
}
}
catch
{
MessageBox.Show("相对路径输入错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//方法二:FileInfo类
FileInfo fi = new FileInfo(pathII);
if (fi.Exists)
fi.Delete();
try
{
using (var fs = fi.Create())
{
byte[] bin = new byte[1024];
new Random().NextBytes(bin);
fs.Write(bin, 0, bin.Length);
}
}
catch
{
MessageBox.Show("相对路径输入错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("文件创建完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//承接以上文件,写入文本
private void writeString_Click(object sender, EventArgs e)
{
/*写入读取数据方法众多
* 1.File,FileInfo类方法
* 2.FileStream
* 3.辅助对象StreamWriter,StreamWriter,BinaryWriter,BinaryReader
* 步骤:
* 1.打开或创建,获取流对象
* 2.构造写入读取器,或者直接写入读取
* 3.关闭并释放
*/
if(string.IsNullOrWhiteSpace(fileContent.Text))
{
MessageBox.Show("请输入写入内容!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if(string.IsNullOrWhiteSpace(filePath.Text))
{
MessageBox.Show("请输入文件路径!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//获取路径以及要写入的内容
string contentText = fileContent.Text;
string path = filePath.Text + "I";
//文件流操作(注意模式可以是追加,覆盖,创建等等......)
FileStream fs = File.Open(path,FileMode.Append,FileAccess.Write);
//构造写入器
StreamWriter sw = new StreamWriter(fs,Encoding.UTF8);
sw.Write(contentText);
//释放所有资源
sw.Dispose();
fs.Dispose();
MessageBox.Show("文本写入成功!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//删除文件操作,比较简单
private void deleteFile_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(filePath.Text))
{
MessageBox.Show("请输入文件路径!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string pathI = filePath.Text + "I";
string pathII = filePath.Text + "II";
if (File.Exists(pathI))
File.Delete(pathI);
if (File.Exists(pathII))
File.Delete(pathII);
MessageBox.Show("文件删除完成!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//写入二进制数据(注意游标的位置以及长度即可)
private void writeBinary_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(fileContent.Text))
{
MessageBox.Show("请输入写入内容!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrWhiteSpace(filePath.Text))
{
MessageBox.Show("请输入文件路径!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//获取路径以及要写入的内容
string contentText = fileContent.Text;
string path = filePath.Text + "I";
//文件流操作(注意模式可以是追加,覆盖,创建等等......)
FileStream fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(Encoding.UTF8.GetBytes(contentText));
bw.Dispose();
fs.Dispose();
MessageBox.Show("二进制文本写入成功!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//读取文件(兼容二进制与文本)
private void readFile_Click(object sender, EventArgs e)
{
//安全性检查
if (string.IsNullOrWhiteSpace(filePath.Text))
{
MessageBox.Show("请输入文件路径!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string path = filePath.Text;
fileContent.Text = "";//清空文本框
BinaryReader br;
try
{
br = new BinaryReader(new FileStream(path,FileMode.Open));
try
{
fileContent.Text = Encoding.UTF8.GetString(br.ReadBytes(1024));
}
catch
{
MessageBox.Show("读取失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
br.Dispose();
}
catch
{
MessageBox.Show("指定的文件不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
//内存流(MemoryFile)
private void readMemoryStream_Click(object sender, EventArgs e)
{
Random rand = new Random();
MemoryStream ms = new MemoryStream();
using(Bitmap bitmap=new Bitmap(pictureBox.Width,pictureBox.Height))
{
Graphics g = Graphics.FromImage(bitmap);
Pen myPen = new Pen(Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255)), rand.Next(4));
g.DrawEllipse(myPen, new Rectangle(rand.Next(20), rand.Next(20),50+ rand.Next(80), 20+rand.Next(100)));
g.Dispose();
bitmap.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
}
this.pictureBox.Image = Image.FromStream(ms);
ms.Dispose();
}
//内存映像文件
private void writeMappedFile_Click(object sender, EventArgs e)
{
if(string.IsNullOrWhiteSpace(MappedFileText.Text))
{
MessageBox.Show("输入要写入的内容!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
byte[] buffer=Encoding.UTF8.GetBytes(MappedFileText.Text);
int len=buffer.Length;
MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("MyFile",1024);
using(MemoryMappedViewStream mms=mmf.CreateViewStream())
{
//先写入长度
mms.Write(BitConverter.GetBytes(len),0,4);
//再写入正文
mms.Write(buffer,0,len);
}
MessageBox.Show("内存映像写入成功!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void readMappedFile_Click(object sender, EventArgs e)
{
//此处使用内存流保留数据
MemoryStream ms = new MemoryStream();
try
{
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("MyFile");
using (MemoryMappedViewStream mms = mmf.CreateViewStream())
{
byte[] len = new byte[4];
mms.Read(len, 0, 4);
int textLen = BitConverter.ToInt32(len, 0);
byte[] data = new byte[textLen];
mms.Read(data, 0, textLen);
//内存流保存,即时被销毁,已经安全存储数据
ms.Write(data, 0, textLen);
}
}
catch
{
MessageBox.Show("内存映射文件还没有创建!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//从内存流中读取
MappedFileText.Text = Encoding.UTF8.GetString(ms.ToArray());
MessageBox.Show("内存映像读取成功!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//程序独立存储区域
private void WriteIsolatedFile_Click(object sender, EventArgs e)
{
if(IsolatedStorageText.Text=="")
{
MessageBox.Show("输入要写入的内容!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
byte[] data = Encoding.UTF8.GetBytes(IsolatedStorageText.Text);
using(IsolatedStorageFile iStoreFile=IsolatedStorageFile.GetUserStoreForAssembly())
{
if(iStoreFile.FileExists("MyFile.txt"))
{
iStoreFile.DeleteFile("MyFile.txt");
}
using(IsolatedStorageFileStream issf=iStoreFile.CreateFile("MyFile.txt"))
{
issf.Write(data, 0, data.Length);
}
}
MessageBox.Show("独立文件创建完毕!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
//读取内存区域
private void ReadIsolatedFile_Click(object sender, EventArgs e)
{
try
{
using (IsolatedStorageFile iStoreFile = IsolatedStorageFile.GetUserStoreForAssembly())
{
using (IsolatedStorageFileStream issf = iStoreFile.OpenFile("MyFile.txt",FileMode.Open))
{
byte[] data=new byte[1024];
issf.Read(data,0,data.Length);
IsolatedStorageText.Text = Encoding.UTF8.GetString(data);
}
}
MessageBox.Show("独立文件读取完毕!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
//移除独立区域
private void RemoveIsolatedFile_Click(object sender, EventArgs e)
{
try
{
using (IsolatedStorageFile iStoreFile = IsolatedStorageFile.GetUserStoreForAssembly())
{
iStoreFile.Remove();
}
MessageBox.Show("独立文件释放完毕!", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}