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); } } } } } }
原文地址:https://www.cnblogs.com/hllxy/p/8317637.html