我從openfiledialoge中選擇文件並在文本框中顯示它在文本框中的名稱delete
button我收到異常The process cannot access the file because it is being used by another process.
我搜索了很多這個異常來解決,但我沒有罰款任何他們的工作,當我試圖關閉文件與imagename這是在文本框,即文件我顯示在picturebox;使用方法,這將關閉並刪除特定的目錄路徑的所有文件,但我怎麼能刪除圖片框所示的唯一文件,我要去的地方錯了刪除顯示在圖片箱中的文件
public partial class RemoveAds : Form
{
OpenFileDialog ofd = null;
string path = @"C:\Users\Monika\Documents\Visual Studio 2010\Projects\OnlineExam\OnlineExam\Image\"; // this is the path that you are checking.
public RemoveAds()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (System.IO.Directory.Exists(path))
{
ofd = new OpenFileDialog();
ofd.InitialDirectory = path;
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
txtImageName.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
}
}
else
{
return;
}
}
private void button2_Click(object sender, EventArgs e)
{
//Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
if (Directory.Exists(path))
{
var directory = new DirectoryInfo(path);
foreach (FileInfo file in directory.GetFiles())
{ if(!IsFileLocked(file))
file.Delete();
}
}
}
public static Boolean IsFileLocked(FileInfo path)
{
FileStream stream = null;
try
{ //Don't change FileAccess to ReadWrite,
//because if a file is in readOnly, it fails.
stream = path.Open (FileMode.Open, FileAccess.Read, 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;
}
}
預先感謝任何幫助
我正在使用另一種形式保存圖像,因此在保存後還是僅在刪除和刪除時才需要處理圖像? – Durga
@Durga我不明白你的意思。如果你還有其他問題,發佈另一個問題是最好的選擇 - 顯示你在那裏討論的代碼。在這種情況下(上圖),本地變量'img'正在處理 - Bitmap對象的實例,而不是它創建的文件。以後不要使用它,因爲它是一個局部變量,它超出了範圍。 –
我明白你的意思,這是非常乾淨的答案,整齊地解釋,得到我如何正確地做它正確的方式非常感謝你 – Durga