簡體   English   中英

如何持續檢查文件是否被刪除,如果沒有被刪除,請重試

[英]How can I continuously check whether a file gets deleted and if it didn't get deleted try again

在我當前的項目中,我遇到隨機錯誤,抱怨有問題的文件正在被其他進程使用。

有時它動作很快,一切都很好,有時它不起作用並不斷給我錯誤

該文件正被另一個進程使用

所以我想我將 delete 方法放在try-catch ,在 catch 中,我有某種循環可以嘗試刪除文件,甚至更好:解鎖它並使其准備好被刪除。

我不知道在該循環中是否會出現另一個異常,以及如何管理它。 如何找到從文件中分離該進程並使其准備好刪除的解決方案?

更新

這是我目前的代碼:

 private void Test(string imagePath)
 {
        try
        {
            if (File.Exists(imagePath))
            {
                pictureBoxExistingPicture.Visible = true;
                labelnew.Visible = true;
                labelold.Visible = true;
                pictureBoxExistingPicture.Image = ImageUtility.SafeLoadImage(imagePath);

                if (MessageBox.Show("Do you want to overwrite the existing image?", "warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                {
                    pictureBoxExistingPicture.Image = Properties.Resources._default;//restore default

                    while (true)
                    {
                        try
                        {
                            File.Delete(imagePath);
                            break;
                        }
                        catch (Exception)
                        {
                        }
                    }

                    pictureBoxHonarjo.Image.Save(imagePath);
                }
                else
                {
                    pictureBoxHonarjo.Image = ImageUtility.SafeLoadImage(imagePath);//restore original image
                }

                pictureBoxExistingPicture.Visible = false;
                labelnew.Visible = false;
                labelold.Visible = false;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

在主題的當前上下文中,我需要說的是,如果用戶希望替換圖像,則應該完成,並且不應該花費很長時間,也不應該失敗。所以基本上當有人嘗試時改變一張圖片,它必須在很短的時間內得到改變。

對於SafeLoadImage函數,這是我的實現:

public class ImageUtility
{
   public static byte[] ImageToBytes(string FilePath, int FileLength)
   {
      FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
      BinaryReader breader = new BinaryReader(fileStream);
      return breader.ReadBytes(FileLength);
    }

    public static Image SafeLoadImage(string imagePath)
    {
        byte[] image_byte;
        Image image;
        FileInfo fileinfo = new FileInfo(imagePath);
        image_byte = ImageUtility.ImageToBytes(imagePath, (int)fileinfo.Length);
        image = ImageUtility.BytesToImage(image_byte);
        return image;
    }
}

所以你有一些偽代碼,例如:

success = false
while not success
..try
..  delete file
..  success = true
..catch
..  wait a second
while end

你可以添加一個重試計數器,這樣它就不會無休止地循環等等,運氣好的話你可以猜到哪里。

我故意不包含代碼,因為您沒有提供自己的代碼,但是給了您一個可以嘗試的模板

這是一個嘗試刪除文件的循環:

protected virtual bool IsFileLocked(FileInfo file) 

{ FileStream 流 = null;

try 
{ 
    stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
} 
catch (IOException) 
{ 
    //the file is unavailable because it is: 
    //still being written to 
    //or being processed by another thread 
    //or does not exist (has already been processed) 
    return true; 
} 
finally 
{ 
    if (stream != null) 
        stream.Close(); 
} 

//file is not locked 
return false; 

}

FileInfo file = new FileInfo("PathToTheFile"); 
while (IsFileLocked(file)) 
    Thread.Sleep(1000); 
file.Delete(); 

您還可以使用進程資源管理器了解哪個進程訪問文件http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

ImageUtility.ImageToBytes完成后不處理 FileStream

難道這是鎖定文件?

public static byte[] ImageToBytes(string FilePath, int FileLength) 
{ 
    FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read); 
    BinaryReader breader = new BinaryReader(fileStream); 
    return breader.ReadBytes(FileLength); 
}

考慮將在執行退出代碼塊后釋放資源的using語句(它包裝 IDisposable 並為您調用 dispose 方法):

public static byte[] ImageToBytes(string FilePath, int FileLength) 
{ 
    using(FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read)) 
    {
        BinaryReader breader = new BinaryReader(fileStream); 
        return breader.ReadBytes(FileLength); 
    }
}

這可能是您的文件被鎖定的原因。

當然,如果其他人正在鎖定您的文件,那么這可能沒用:) 但我懷疑這些是您創建/正在處理的圖像文件

我使用 MessageBox 的簡單解決方案:

bool deleted= false;
while(!deleted)
{
 try
  {
    File.Delete("path to file");                                 
    deleted = true;
  }
 catch 
  {
    MessageBox.Show("You can't delete file. Close file and press 'OK'");
    deleted = false; 
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM