c#,文件读写之前已检测占用,按道理没占用后才开始读写,但是还是出现了被占用的情况

         //检测文件被占用的对象//判断文件是否被占用
        while (IsFileInUse(elasticmodelad))
        {
            Thread.Sleep(100);
        }

        //写入!!!!还是显示被占用
        using (StreamWriter swe = new StreamWriter(elasticmodelad,true))
        {
                  。。。。。
         }

并发写文件请求多的话最好不用文件,开了多个程序后,线程检查这种谁也没法保证检查没有占用,下一句代码就能正常打开文件。

你先用独占的方式打开它,再进行操作,避免你操作了一半别的进程又打开了


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using System.IO;
using System.Runtime.InteropServices; 
 
namespace FileStatusTest
{
    public class FileStatusHelper
    {
        [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 static readonly IntPtr HFILE_ERROR = new IntPtr(-1);  
 
        /// <summary>
        /// 查看文件是否被占用
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool IsFileOccupied(string filePath)
        {
            IntPtr vHandle = _lopen(filePath, OF_READWRITE | OF_SHARE_DENY_NONE);
            CloseHandle(vHandle);
            return vHandle == HFILE_ERROR ? true : false;
        }
    }
}
//调用
if (FileStatusHelper.IsFileOccupied(@"文件路径"))
{
    MessageBox.Show("文件已被占用");
}
else
{
    MessageBox.Show("文件未被占用");
}