系统特殊目录路径

//取得特殊文件夹的绝对路径
//桌面
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//收藏夹
Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
//我的文档
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//最近使用的文档
Environment.GetFolderPath(Environment.SpecialFolder.Recent);

文件操作

void CheckFileExists()
{
//通过函数File.Exists方法判断文件是否存在
//string fileName = @"C:\Dell\demo.txt";
//if (File.Exists(fileName))
//{
// Console.WriteLine("File {0} exists.", fileName);
//}
string fileName = @"C:\Dell\demo.txt";
if (File.Exists(fileName))
this.tbInfo.AppendText(fileName + "存在\r\n"); else
this.tbInfo.AppendText(fileName + "不存在\r\n");
}
void GetFileInfo()
{
//通过FileInfo取得文件属性
string fileName = this.tbFile.Text;
FileInfo info = new FileInfo(fileName);
// 判断文件是否存在
this.tbInfo.AppendText("文件是否存在:" + info.Exists.ToString() + "\r\n");
// 获取文件名
this.tbInfo.AppendText("文件名:" + info.Name + "\r\n");
// 获取文件扩展名
this.tbInfo.AppendText("扩展名:" + info.Extension + "\r\n");
// 获取文件躲在文件夹
this.tbInfo.AppendText("所在文件夹:" + info.Directory.Name + "\r\n");
// 获取文件长度
this.tbInfo.AppendText("文件长度:" + info.Length + "\r\n");
// 获取或设置文件是否只读
this.tbInfo.AppendText("是否只读:" + info.IsReadOnly + "\r\n");
// 获取或设置文件创建时间
this.tbInfo.AppendText("创建时间:" + info.CreationTime + "\r\n");
// 获取或设置文件最后一次访问时间
this.tbInfo.AppendText("最后一次访问时间:" + info.LastAccessTime + "\r\n");
// 获取或设置文件最后一次写入时间
this.tbInfo.AppendText("最后一次写入时间:" + info.LastWriteTime + "\r\n");
}
void CopyFile()
{
// 复制文件
// 原文件
string sourceFileName = @"C:\Users\Dell\Desktop\timer.png";
// 新文件
string destFileName = @"e:\timer.png";
File.Copy(sourceFileName, destFileName);
}
void MoveFile()
{
// 移动文件,可以跨卷标移动
// 文件移动后原文件被删除
string sourceFileName = @"C:\Users\Dell\Desktop\timer.png";
string destFileName = @"e:\timer.png";
File.Move(sourceFileName, destFileName);
}
void DeleteFile()
{
//删除指定文件
string fileName = @"C:\Dell\demo.txt";
// 删除前需检查文件是否存在
if (File.Exists(fileName))
File.Delete(fileName);
}
void PickFile()
{
//从工具箱拖入OpenFileDialog控件命名为ofd,或者直接定义
OpenFileDialog ofd = new OpenFileDialog();
// 当所选文件不存在时给出警告提示
ofd.CheckFileExists = true;
// 是否添加默认文件扩展名
ofd.AddExtension = true;
// 设置默认扩展文件名
ofd.DefaultExt = ".txt";
// 设置文件类型筛选规则,
// 组与组之间用“|”分隔,每组中文件类型与扩展名用“|”分割,多个文件类型用“;”分隔
ofd.Filter = "文本文件|*.txt|图片文件|*.png;*gif;*.jpg;*.jpeg;*.bmp";
// 设置是否支持多选
ofd.Multiselect = true;
// 设置对话框标题
ofd.Title = "选择文件:";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.tbFile.Text = ofd.FileName;
// 依次列出多选的文件名称
foreach (string fname in ofd.FileNames)
{
this.tbInfo.AppendText(fname + "\r\n");
}
}
}
void RenameFile()
{
// 使用VB方法,重命名文件
Computer myPC = new Computer();
string sourceFileName = @"C:\Users\Dai\Desktop\截图\timer.png";
string newFileName = @"timer12.png";
//必须是名称,而不是绝对路径
myPC.FileSystem.RenameFile(sourceFileName, newFileName);
myPC = null;
}

文件夹操作

#region 文件夹操作
/// <summary>
/// 选择路径
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOpenDir_Click(object sender, EventArgs e)
{
// 从工具箱拖入一个FolderBrowserDialog,命名为fbd。除了拖入,还可直接定义
FolderBrowserDialog fbd = new FolderBrowserDialog();
// 设置文件夹选择框提示文本
fbd.Description = "请选择一个文件夹:";
// 设置默认位置为桌面
fbd.RootFolder = Environment.SpecialFolder.DesktopDirectory;
// 设置是否显示“新建文件夹”按钮
fbd.ShowNewFolderButton = false;
// 设置默认选中的文件夹为本地目录
fbd.SelectedPath = @"e:\";
// 设置默认选中的文件夹为网络路径
//this.fbd.SelectedPath = @"\\192.168.1.1\";
// 显示对话框,并返回已选中的文件夹
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.tbDir.Text = fbd.SelectedPath;
}
}
/// <summary>
/// 文件夹属性
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetDirInfo_Click(object sender, EventArgs e)
{
string dirName = this.tbDir.Text;
if (string.IsNullOrEmpty(dirName))
{
this.tbInfo.AppendText("文件夹不能空\r\n");
return;
}
// 检查文件夹是否存在
if (Directory.Exists(dirName))
{
// 根据路径获得文件夹属性
DirectoryInfo info = new DirectoryInfo(dirName);
this.tbInfo.AppendText(string.Format("完整路径:{0}\r\n", info.FullName));
this.tbInfo.AppendText(string.Format("获取目录的根:{0}\r\n", info.Root));
this.tbInfo.AppendText(string.Format("获取目录的父目录:{0}\r\n", info.Parent));
this.tbInfo.AppendText(string.Format("创建时间:{0}\r\n", info.CreationTime));
this.tbInfo.AppendText(string.Format("最后一次访问时间:{0}\r\n", info.LastAccessTime));
this.tbInfo.AppendText(string.Format("最后一次写入时间:{0}\r\n", info.LastWriteTime));
} else
{
this.tbInfo.AppendText(string.Format("文件夹不存在{0}\r\n", dirName));
}
}
/// <summary>
/// 文件夹权限
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetDirSec_Click(object sender, EventArgs e)
{
//取得文件夹的访问权限
string dirName = this.tbDir.Text;
if (string.IsNullOrEmpty(dirName))
{
this.tbInfo.AppendText("文件夹不能空\r\n");
return;
}
DirectoryInfo dirInfo = new DirectoryInfo(dirName);
// 需引用命名空间System.Security.AccessControl;
// 取得访问控制列表ACL信息
DirectorySecurity sec = dirInfo.GetAccessControl(AccessControlSections.Access);
foreach (FileSystemAccessRule rule in
sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
// 文件夹名称
tbInfo.AppendText(dirName + "\t");
// 取得Windows账号或sid
tbInfo.AppendText(rule.IdentityReference.Value + "\t");
// 取得文件夹权限
tbInfo.AppendText(rule.FileSystemRights.ToString() + "\r\n");
}
}
/// <summary>
/// 遍历子文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetDirFiles_Click(object sender, EventArgs e)
{
string dirName = this.tbDir.Text;
if (string.IsNullOrEmpty(dirName))
{
this.tbInfo.AppendText("文件夹不能空\r\n");
return;
}
//遍历文件夹中的文件
DirectoryInfo info = new DirectoryInfo(dirName);
foreach (FileInfo fInfo in info.GetFiles())
{
this.tbInfo.AppendText(fInfo.FullName + "\r\n");
}
}
/// <summary>
/// 遍历子文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetSubDir_Click(object sender, EventArgs e)
{
string dirName = this.tbDir.Text;
if (string.IsNullOrEmpty(dirName))
{
this.tbInfo.AppendText("文件夹不能空\r\n");
return;
}
//遍历文件夹中的子文件夹
DirectoryInfo info = new DirectoryInfo(dirName);
foreach (DirectoryInfo dInfo in info.GetDirectories())
{
this.tbInfo.AppendText(dInfo.FullName + "\r\n");
}
}
/// <summary>
/// 遍历全部子文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetAllSubDir_Click(object sender, EventArgs e)
{
string dirName = this.tbDir.Text;
if (string.IsNullOrEmpty(dirName))
{
this.tbInfo.AppendText("文件夹不能空\r\n");
return;
}
//使用递归方法遍历文件夹中所有的子文件夹
DirectoryInfo info = new DirectoryInfo(dirName);
foreach (DirectoryInfo dInfo in info.GetDirectories())
{
//ReadDirs(dInfo.FullName);
ReadDirs(dInfo.FullName,);
this.tbInfo.AppendText(dInfo.FullName + "\r\n");
}
}
private void ReadDirs(string dirName)
{
// 递归读取子文件夹
DirectoryInfo info = new DirectoryInfo(dirName);
foreach (DirectoryInfo dInfo in info.GetDirectories())
{
ReadDirs(dInfo.FullName);
this.tbInfo.AppendText(dInfo.FullName + "\r\n");
}
}
private void ReadDirs(string dirName, int level)
{
// 记录文件夹读取深度
level++;
// 当遍历深度小于设定值时才继续读取
if (level < totalLevel)
{
DirectoryInfo info = new DirectoryInfo(dirName);
#region 显示文件信息
foreach (FileInfo fInfo in info.GetFiles())
{
this.tbInfo.AppendText(fInfo.FullName + "\r\n");
}
#endregion
#region 显示子文件夹
foreach (DirectoryInfo dInfo in info.GetDirectories())
{
ReadDirs(dInfo.FullName, level);
this.tbInfo.AppendText(dInfo.FullName + "\r\n");
}
#endregion
}
}
/// <summary>
/// 删除文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeleteDir_Click(object sender, EventArgs e)
{
string dirName = this.tbDir.Text;
if (string.IsNullOrEmpty(dirName))
{
this.tbInfo.AppendText("文件夹不能空\r\n");
return;
}
if (Directory.Exists(dirName))
{
if(MessageBox.Show("您确定要删除指定文件夹吗?","确认框",
MessageBoxButtons.YesNo,MessageBoxIcon.Question)
== System.Windows.Forms.DialogResult.Yes)
{
Directory.Delete(dirName);
}
}
}
/// <summary>
/// 移动文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMoveDir_Click(object sender, EventArgs e)
{
string dirName = this.tbDir.Text;
if (string.IsNullOrEmpty(dirName))
{
this.tbInfo.AppendText("文件夹不能空\r\n");
return;
}
if (Directory.Exists(dirName))
{
if (MessageBox.Show("您确定要移动文件夹吗?", "确认框",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== System.Windows.Forms.DialogResult.Yes)
{
//源路径和目标路径必须具有相同的根。移动操作在卷之间无效
Directory.Move(dirName, @"C:\Users\Dai\Desktop\截图222");
}
}
}
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreateDir_Click(object sender, EventArgs e)
{
// appPath = System.Windows.Forms.Application.StartupPath + "\\";
string dirName = appPath + DateTime.Now.ToString("yyyyMMddHHmmss");
Directory.CreateDirectory(dirName);
this.tbInfo.AppendText(string.Format("当前工作目录:{0}\r\n", Directory.GetCurrentDirectory()));
Directory.SetCurrentDirectory(@"c:\");
Directory.CreateDirectory(DateTime.Now.ToString("yyyyMMddHHmmss"));
this.tbInfo.AppendText(string.Format("已创建文件夹{0}\r\n", dirName));
}
/// <summary>
/// 特殊文件夹路径
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnFolderPath_Click(object sender, EventArgs e)
{
//取得特殊文件夹的绝对路径
this.tbInfo.AppendText(string.Format("特殊文件夹路径\r\n桌面:{0}\r\n", Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
this.tbInfo.AppendText(string.Format("收藏夹:{0}\r\n", Environment.GetFolderPath(Environment.SpecialFolder.Favorites)));
this.tbInfo.AppendText(string.Format("我的文档:{0}\r\n", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)));
this.tbInfo.AppendText(string.Format("最近使用的文档:{0}\r\n", Environment.GetFolderPath(Environment.SpecialFolder.Recent)));
//取得特殊文件夹的绝对路径
//桌面
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//收藏夹
Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
//我的文档
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//最近使用的文档
Environment.GetFolderPath(Environment.SpecialFolder.Recent);
}
/// <summary>
/// 重命名
/// </summary>
void RenameDirectory()
{
// 重命名文件夹
Computer myPC = new Computer();
string sourceDirName = @"C:\Users\Dell\Desktop\截图";
string newDirName = @"截图";
//必须是名称,而不是绝对路径
myPC.FileSystem.RenameDirectory(sourceDirName, newDirName);
myPC = null;
}
private void btnRenameDir_Click(object sender, EventArgs e)
{
RenameDirectory();
}

文件读写

读取文件

FileStream

try
{
// 以只读模式打开文本文件
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[fs.Length];
int numBytesToRead = (int)fs.Length;
int numBytesRead = ;
while (numBytesToRead > )
{
int n = fs.Read(bytes, numBytesRead, numBytesToRead);
if (n == )
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
// 以UTF-8编码解码
//string content = Encoding.UTF8.GetString(bytes);
// 以GBK方式读取
string content = Encoding.GetEncoding("GBK").GetString(bytes);
fs.Close();
MessageBox.Show(content);
}
}
catch (System.IO.FileNotFoundException ioex)
{
MessageBox.Show("文件不存在","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show("其他错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
}

StreamReader

StreamReader sr = new StreamReader(fileName, Encoding.UTF8);
string line;
// 逐行读取
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line.ToString());
}
sr.Close();

ReadAllText

if (System.IO.File.Exists(fileName))
{
// 默认以UTF-8编码读取
//string content = System.IO.File.ReadAllText(fileName);
// 以汉字GBK编码读取
string content = System.IO.File.ReadAllText(fileName,Encoding.GetEncoding("GBK"));
MessageBox.Show(content);
}

ReadAllLines

// 读取所有行
foreach (var line in File.ReadAllLines(fileName))
{
Console.WriteLine(line);
}

写入文件

FileStream

// 以追加模式打开文件,当文件不存在时创建它
using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
{
string content = "跟我一起做项目";
// 以UTF-8编码写入
//fs.Write(Encoding.UTF8.GetBytes(content), 0, Encoding.UTF8.GetByteCount(content));
// 以GBK编码写入
fs.Write(Encoding.GetEncoding("GBK").GetBytes(content), ,
Encoding.GetEncoding("GBK").GetByteCount(content));
fs.Close();
MessageBox.Show("已写入");
}

StreamWriter

StreamWriter sw = File.AppendText(fileName);
//开始写入
sw.Write("跟我一起做项目\r\n");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();

AppendAllText

// 如果文件存在则追加文本
// 如果文件不存在则创建文件,并写入文本
// 默认以UTF-8编码写入
//File.AppendAllText(fileName, "追加文本\r\n",Encoding.UTF8);
// 如果字符集选择了ASCII,那么写入的汉字将编程乱码
//File.AppendAllText(fileName, "追加文本\r\n", Encoding.ASCII);
// 以GBK编码写入
File.AppendAllText(fileName, "追加文本\r\n", Encoding.GetEncoding("GBK"));

图像操作

图片打水印

private void btnWrite_Click(object sender, EventArgs e)
{
// 从图片文件创建一个Image对象
Image img = System.Drawing.Image.FromFile(imgName);
// 创建一个Bitmap对象
Bitmap bmp = new Bitmap(img);
// 及时销毁img
img.Dispose();
// 从bpm创建一个Graphics对象
Graphics graphics = Graphics.FromImage(bmp);
// 指定在缩放或旋转图像时使用的算法
// 使用高质量的双线性插值法。执行预筛选以确保高质量的收缩。
// 需引用System.Drawing.Drawing2D
graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
// 定义单色画笔,用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。
SolidBrush brush = new SolidBrush(Color.Red);
// 定义起始位置
PointF P = new PointF(, );
// 定义字体
Font font = new Font("微软雅黑", );
// 绘制字符
graphics.DrawString("这是绘制的文字", font, brush, P);
// 以jpeg格式保存图像文件
// System.Drawing.Imaging
//bmp.Save(newImgName,ImageFormat.Jpeg);
bmp.Save(newImgName, ImageFormat.Gif);
// 销毁对象
font.Dispose();
graphics.Dispose();
img.Dispose();
this.pictureBox1.Image = bmp;
}

修改图片格式

private void btnSaveAs_Click(object sender, EventArgs e)
{
string imgName = appPath + "Penguins.jpg";
Image img = System.Drawing.Image.FromFile(imgName);
// 创建一个Bitmap对象
Bitmap bmp = new Bitmap(img);
// 另存为gif格式
bmp.Save(appPath + "Penguins_new.gif", ImageFormat.Gif);
// 另存为png格式
bmp.Save(appPath + "Penguins_new.png", ImageFormat.Png);
// 另存为bmp格式
bmp.Save(appPath + "Penguins_new.bmp", ImageFormat.Bmp);
// 销毁对象
img.Dispose();
}

创建缩略图

private void btnThumbnail_Click(object sender, EventArgs e)
{
// 从图片文件创建image对象
Image img = Image.FromFile(imgName);
// 创建缩略图,指定宽度和长度
// 提供一个回调方法,用于确定 GetThumbnailImage 方法应在何时提前取消执行
Image thumbnailImage = img.GetThumbnailImage(, ,
new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
thumbnailImage.Save(appPath + "Penguins_thum.jpg", ImageFormat.Jpeg);
thumbnailImage.Dispose();
img.Dispose();
}

最新文章

  1. 【ZZ】 DShader之位移贴图(Displacement Mapping)
  2. 《我是一只it小小鸟》
  3. wildfly9 配置SSL单向认证/https
  4. CAD文件导入AD09
  5. 变量数据是怎么进ARM中的RAM中?
  6. Rainmeter 雨滴桌面 主题分享
  7. mysql 分区 按 PARTITION BY RANGE (TO_DAYS(startTime))
  8. MAC使用小技巧(二)
  9. vue.js源码精析
  10. AVFoundation--AVPlayer
  11. 教我徒弟Android开发入门(三)
  12. C# 设置Word文档保护(加密、解密、权限设置)
  13. 第一章:python基础语法| 字符编码| 条件语句...
  14. USACO 好题汇总
  15. AGC001 E - BBQ Hard 组合数学
  16. do while
  17. Python 类的约束
  18. Robotium_断言方法assert、is、search
  19. windows下用qemu搭建android
  20. [转]Creating a custom ribbon for Outlook 2013, 2010 and toolbar for Outlook 2007, 2003 – C# sample

热门文章

  1. [ZLXOI2015]殉国 数论 扩展欧几里得
  2. python黑科技:还在为没有wifi而烦心吗?这篇文章解决你的困扰
  3. Django 项目搭建(ubuntu系统)
  4. set的便捷操作
  5. vue2.0 axios封装、vuex介绍
  6. C# - 如何让类型可以比较
  7. 深入理解java虚拟机之java内存区域
  8. 离线安装mysql数据库
  9. 浏览器加载 CommonJS 模块的原理与实现
  10. asp.net core系列 43 Web应用 Session分布式存储(in memory与Redis)