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); } } } } } }
  • 相关阅读:
    C#/Net代码精简优化技巧(二)【转】
    IsSpecialName特性及其他问题【转】
    &、|与&&、||的比较
    序列化后存储Cookie
    序列化反序列化操作
    C#/Net代码精简优化技巧(一)【转】
    .Net 中的序列化与反序列化【转】
    c#对象序列化(二进制序列化)BinaryFormatter【转】
    POJ 2828 Buy Tickets(单点更新) 详细题解和思路
    Color the ball HDU 1556 (非线段树做法)
  • 原文地址:https://www.cnblogs.com/hllxy/p/8317637.html
Copyright © 2011-2022 走看看