zoukankan      html  css  js  c++  java
  • 如何判断文件是否在占用?

    使用托管方法来实现。

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

    结果如下:

  • 相关阅读:
    JVM(5)之 GC之标记
    JVM(4)之 使用MAT排查堆溢出
    JVM(3) 之 内存分配与回收策略
    JVM(2)之 JAVA堆
    JVM(1)之 JAVA栈
    MySQL查询时报错Illegal mix of collations
    struts2 基础学习
    python3.4 + pycharm安装与使用
    Pycharm激活
    IntelliJ IDEA 2018.2激活
  • 原文地址:https://www.cnblogs.com/mingle/p/2959543.html
Copyright © 2011-2022 走看看