c#文件图片操作

系统特殊目录路径

//取得特殊文件夹的绝对路径
//桌面
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:Delldemo.txt";
    //if (File.Exists(fileName))
    //{
    //    Console.WriteLine("File {0} exists.", fileName);
    //}
    string fileName = @"C:Delldemo.txt";
    if (File.Exists(fileName))
                    this.tbInfo.AppendText(fileName + "存在
"); else
                    this.tbInfo.AppendText(fileName + "不存在
");
}
void GetFileInfo() 
{
    //通过FileInfo取得文件属性
    string fileName = this.tbFile.Text;
    FileInfo info = new FileInfo(fileName);
    // 判断文件是否存在
    this.tbInfo.AppendText("文件是否存在:" + info.Exists.ToString() + "
");
    // 获取文件名
    this.tbInfo.AppendText("文件名:" + info.Name + "
");
    // 获取文件扩展名
    this.tbInfo.AppendText("扩展名:" + info.Extension + "
");
    // 获取文件躲在文件夹
    this.tbInfo.AppendText("所在文件夹:" + info.Directory.Name + "
");
    // 获取文件长度
    this.tbInfo.AppendText("文件长度:" + info.Length + "
");
    // 获取或设置文件是否只读
    this.tbInfo.AppendText("是否只读:" + info.IsReadOnly + "
");
    // 获取或设置文件创建时间
    this.tbInfo.AppendText("创建时间:" + info.CreationTime + "
");
    // 获取或设置文件最后一次访问时间
    this.tbInfo.AppendText("最后一次访问时间:" + info.LastAccessTime + "
");
    // 获取或设置文件最后一次写入时间
    this.tbInfo.AppendText("最后一次写入时间:" + info.LastWriteTime + "
");
}
void CopyFile() 
{
    // 复制文件
    // 原文件
    string sourceFileName = @"C:UsersDellDesktop	imer.png";
    // 新文件
    string destFileName = @"e:	imer.png";
    File.Copy(sourceFileName, destFileName);
}
void MoveFile() 
{
    // 移动文件,可以跨卷标移动
    // 文件移动后原文件被删除
    string sourceFileName = @"C:UsersDellDesktop	imer.png";
    string destFileName = @"e:	imer.png";
    File.Move(sourceFileName, destFileName);
}
void DeleteFile() 
{
    //删除指定文件
    string fileName = @"C:Delldemo.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 + "
");
        }
    }
}
void RenameFile() 
{
    // 使用VB方法,重命名文件
    Computer myPC = new Computer();
    string sourceFileName = @"C:UsersDaiDesktop截图	imer.png";
    string newFileName = @"timer12.png";
    //必须是名称,而不是绝对路径
    myPC.FileSystem.RenameFile(sourceFileName, newFileName);
    myPC = null;
}
View Code

文件夹操作

#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("文件夹不能空
");
        return;
    }
    // 检查文件夹是否存在
    if (Directory.Exists(dirName)) 
    {
        // 根据路径获得文件夹属性
        DirectoryInfo info = new DirectoryInfo(dirName);
        this.tbInfo.AppendText(string.Format("完整路径:{0}
", info.FullName));
        this.tbInfo.AppendText(string.Format("获取目录的根:{0}
", info.Root));
        this.tbInfo.AppendText(string.Format("获取目录的父目录:{0}
", info.Parent));
        this.tbInfo.AppendText(string.Format("创建时间:{0}
", info.CreationTime));
        this.tbInfo.AppendText(string.Format("最后一次访问时间:{0}
", info.LastAccessTime));
        this.tbInfo.AppendText(string.Format("最后一次写入时间:{0}
", info.LastWriteTime));
    } else 
    {
        this.tbInfo.AppendText(string.Format("文件夹不存在{0}
", 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("文件夹不能空
");
        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 + "	");
        // 取得Windows账号或sid
        tbInfo.AppendText(rule.IdentityReference.Value + "	");
        // 取得文件夹权限
        tbInfo.AppendText(rule.FileSystemRights.ToString() + "
");
    }
}
/// <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("文件夹不能空
");
        return;
    }
    //遍历文件夹中的文件
    DirectoryInfo info = new DirectoryInfo(dirName);
    foreach (FileInfo fInfo in info.GetFiles()) 
    {
        this.tbInfo.AppendText(fInfo.FullName + "
");
    }
}
/// <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("文件夹不能空
");
        return;
    }
    //遍历文件夹中的子文件夹
    DirectoryInfo info = new DirectoryInfo(dirName);
    foreach (DirectoryInfo dInfo in info.GetDirectories()) 
    {
        this.tbInfo.AppendText(dInfo.FullName + "
");
    }
}
/// <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("文件夹不能空
");
        return;
    }
    //使用递归方法遍历文件夹中所有的子文件夹
    DirectoryInfo info = new DirectoryInfo(dirName);
    foreach (DirectoryInfo dInfo in info.GetDirectories()) 
    {
        //ReadDirs(dInfo.FullName);
        ReadDirs(dInfo.FullName,0);
        this.tbInfo.AppendText(dInfo.FullName + "
");
    }
}
private void ReadDirs(string dirName) 
{
    // 递归读取子文件夹
    DirectoryInfo info = new DirectoryInfo(dirName);
    foreach (DirectoryInfo dInfo in info.GetDirectories()) 
    {
        ReadDirs(dInfo.FullName);
        this.tbInfo.AppendText(dInfo.FullName + "
");
    }
}
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 + "
");
        }
        #endregion
                #region 显示子文件夹
                        foreach (DirectoryInfo dInfo in info.GetDirectories()) 
        {
            ReadDirs(dInfo.FullName, level);
            this.tbInfo.AppendText(dInfo.FullName + "
");
        }
        #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("文件夹不能空
");
        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("文件夹不能空
");
        return;
    }
    if (Directory.Exists(dirName)) 
    {
        if (MessageBox.Show("您确定要移动文件夹吗?", "确认框", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == System.Windows.Forms.DialogResult.Yes) 
        {
            //源路径和目标路径必须具有相同的根。移动操作在卷之间无效
            Directory.Move(dirName, @"C:UsersDaiDesktop截图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}
", Directory.GetCurrentDirectory()));
    Directory.SetCurrentDirectory(@"c:");
    Directory.CreateDirectory(DateTime.Now.ToString("yyyyMMddHHmmss"));
    this.tbInfo.AppendText(string.Format("已创建文件夹{0}
", dirName));
}
/// <summary>
/// 特殊文件夹路径
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnFolderPath_Click(object sender, EventArgs e) 
{
    //取得特殊文件夹的绝对路径
    this.tbInfo.AppendText(string.Format("特殊文件夹路径
桌面:{0}
", Environment.GetFolderPath(Environment.SpecialFolder.Desktop)));
    this.tbInfo.AppendText(string.Format("收藏夹:{0}
", Environment.GetFolderPath(Environment.SpecialFolder.Favorites)));
    this.tbInfo.AppendText(string.Format("我的文档:{0}
", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)));
    this.tbInfo.AppendText(string.Format("最近使用的文档:{0}
", 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:UsersDellDesktop截图";
    string newDirName = @"截图";
    //必须是名称,而不是绝对路径
    myPC.FileSystem.RenameDirectory(sourceDirName, newDirName);
    myPC = null;
}
private void btnRenameDir_Click(object sender, EventArgs e) 
{
    RenameDirectory();
}
View Code

文件读写

读取文件

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 = 0;
        while (numBytesToRead > 0) 
        {
            int n = fs.Read(bytes, numBytesRead, numBytesToRead);
            if (n == 0)
                            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 
{
}
View Code

StreamReader

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

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);
}
View Code

ReadAllLines

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

写入文件

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), 0, 
        Encoding.GetEncoding("GBK").GetByteCount(content));
    fs.Close();
    MessageBox.Show("已写入");
}
View Code

StreamWriter

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

AppendAllText

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

图像操作

图片打水印

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(250, 300);
    // 定义字体
    Font font = new Font("微软雅黑", 40);
    // 绘制字符
    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;
}
View Code

修改图片格式

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();
}
View Code

创建缩略图

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