zoukankan      html  css  js  c++  java
  • C# 检测文件是否被其他进程占用

    我们在项目中经常会对文件进行增删改的操作。如果文件被占用,进行删除移动等操作时,会抛出异常,我们可以对其进行检测,对用户进行提醒。

    http://blog.csdn.net/snakorse/article/details/19581329看到了如下的用法:

    添加命名空间:
    using System.Runtime.InteropServices;
    在类里面添加:
    //2018-1-19 文件操作 判断文件是否被占用
            [DllImport("kernel32.dll")]
            public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
            [DllImport("kernel32.dll")]
            public static extern bool CloseHandle(IntPtr hObject);
            public const int OF_READWRITE = 2;
            public const int OF_SHARE_DENY_NONE = 0x40;
            public readonly IntPtr HFILE_ERROR = new IntPtr(-1);
    private void btnDelete_Click(object sender, RoutedEventArgs e)
            {
                int[] _intRow = this.tableView1.GetSelectedRowHandles();
    
                if (_intRow == null || _intRow.Length <= 0 || _intRow[0] < 0)
                {
                    MessageBox.Show("请选择你需要删除的数据!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    if (MessageBox.Show(this, "是否删除所选的图片?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == System.Windows.MessageBoxResult.Yes)
                    {
                        for (int i = 0; i < _intRow.Length; i++)
                        {
                            object str = gridImgData.GetCellValue(_intRow[i], "VarPath");
    //判断文件是否占用 IntPtr vHandle
    = _lopen(str.ToString(), OF_READWRITE | OF_SHARE_DENY_NONE); if (vHandle == HFILE_ERROR)//被占用 { if (MessageBox.Show("该图片在工程中已使用,是否确定移动或删除的操作?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == System.Windows.MessageBoxResult.Yes) { try { if (File.Exists(str.ToString()))//如果存在文件 { File.Delete(str.ToString()); } tableView1.DeleteRow(_intRow[i]);//删除列表上的记录 } catch (Exception ex) { string strmsg = string.Format("图片删除失败,原因:{0}", ex.Message); MessageBox.Show(strmsg, "提示", MessageBoxButton.OK, MessageBoxImage.Information); } } else//未被占用 { return; } } else { try { if (File.Exists(str.ToString()))//如果存在文件 { File.Delete(str.ToString()); } tableView1.DeleteRow(_intRow[i]);//删除列表上的记录 } catch (Exception ex) { string strmsg = string.Format("图片删除失败,原因:{0}", ex.Message); MessageBox.Show(strmsg, "提示", MessageBoxButton.OK, MessageBoxImage.Information); } } } } } }
  • 相关阅读:
    ARM汇编指令
    Linux系统里如何彻底的清空终端屏幕?
    Linux命令(16)压缩,解压文件
    Linux命令(18)查看当前用户who、whoami、who am i
    Linux命令(17)du 查看文件和目录磁盘使用情况
    Mongodb(3)插入文档,更新文档,删除文档
    Mongodb(2)创建数据库,删除数据库,创建集合,删除集合,显示文档内容
    Mongodb(1)如何存储以及简介
    Linux命令(15)查看系统版本信息
    Python 结巴分词(2)关键字提取
  • 原文地址:https://www.cnblogs.com/hllxy/p/8317637.html
Copyright © 2011-2022 走看看