반응형
        public static bool IsFileLocked(string filePath)
        {
            return IsFileLocked(new FileInfo(filePath));
        }

        public static bool IsFileLocked(FileInfo file)
        {
            try
            {
                using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    stream.Close();
                }
            }
            catch (IOException)
            {
                return true;
            }

            return false;
        }

        public static bool DeleteFile(string filePath)
        {
            try
            {
                if (!File.Exists(filePath)) return false;

                int count = 0;

                while (true)
                {
                    if (IsFileLocked(filePath))
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        break;
                    }

                    // wait until 2sec
                    if (count++ > 20)
                    {
                        return false;
                    }
                }

                File.Delete(filePath);
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }
반응형

+ Recent posts