• 如何判断文件是否在占用?


    使用托管方法来实现。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.IO;
    
    namespace ALU.C0370A.SimuDID.Common
    {
        public class FileStatus
        {
                [DllImport("kernel32.dll")]
                private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
    
                [DllImport("kernel32.dll")]
                private static extern bool CloseHandle(IntPtr hObject);
    
                private const int OF_READWRITE = 2;
    
                private const int OF_SHARE_DENY_NONE = 0x40;
    
                private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
    
            //Judge whether the file is handled by process now
                public static int FileIsOpen(string fileFullName)
                {
                    if (!File.Exists(fileFullName))
                    {
                        return -1;
                    }
    
                    IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);
    
                    if (handle == HFILE_ERROR)
                    {
                        return 1;
                    }
    
                    CloseHandle(handle);
    
                    return 0;
            }  
        }
    }
    

    测试代码:

    class Program  
    {  
        static void Main(string[] args)  
        {  
            string testFilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"testOpen.txt";  
      
            FileStream fs = new FileStream(testFilePath, FileMode.OpenOrCreate, FileAccess.Read);  
      
            BinaryReader br = new BinaryReader(fs);  
      
            br.Read();  
      
            Console.WriteLine("文件被打开");  
      
            int result =FileStatus.FileIsOpen(testFilePath);  
      
            Console.WriteLine(result);  
      
            br.Close();  
      
            Console.WriteLine("文件被关闭");  
      
            result = FileStatus.FileIsOpen(testFilePath);  
      
            Console.WriteLine(result);  
      
            Console.ReadLine();  
        }  
    }  

    结果如下:

  • 相关阅读:
    linux服务器管理员的12个有用的命令
    登录服务器,首先用到的5个命令
    去掉hive字段中的tab
    html-css实例
    【转】你真的理解Python中MRO算法吗?
    【转】CentOS下expect 安装
    Python|PyCharm安装scrapy包
    Java连接Oracle
    Java连接mysql
    最常用正则表达式
  • 原文地址:https://www.cnblogs.com/mingle/p/2959543.html
Copyright © 2020-2023  润新知