![](/img/trans.png)
[英]Program freezes when running as I try to input file contents into listbox
[英]C# program freezes when I try to delete file which is being used
研究了许多有关此异常的主题,没有运气。 我的简单代码:
string t = Path.GetTempFileName();
t = t.Remove(t.Length - 11, 11);
var q = Directory.EnumerateFiles(t, "tmp????.tmp");
var f = q.ToList();
for (int i = 0; i < q.Count(); i++)
{
// if (Helper.CanReadFile(f[i]))
try
{
File.Delete(f[i]);
}
catch (IOException)
{
break;
}
}
我在mainwindow的Closing事件中运行了这段代码。 因此,它删除了几个文件,进入了异常,然后执行“ break”语句,然后在某个地方。 只是冻结,暂停调试器不会导致任何结果。 我尝试了几段代码来查找是否在删除文件之前使用了该文件,但是在此代码内它会得到一个异常(例如Helper.CanReadFile),并在那里停止程序流。 我真的不必删除所有文件,但我需要停止冻结。 如何处理此异常,以免冻结程序?
一些带有断点和大多数信息的编辑。
1)出现异常http://imgur.com/a/k6of3
2)从它开始的第一步,没什么http://imgur.com/a/FvWjz
3)返回配置http://imgur.com/a/LMdiA
4)返回事件方法http://imgur.com/a/FlIUf
5)从onclose http://imgur.com/a/YQUrZ调用
6)之后,它在这里循环一会(我使用全局热键) http://imgur.com/a/0qjdf它在〜10次循环后以msg = 130熄灭。如果我删除文件删除部分,我的程序会关闭。
7)冻结的部分(没有代码正在运行消息) http://imgur.com/a/WeEGj
删除文件时,您可以尝试以下操作:
要在后台线程上运行此代码,您可以执行以下几项操作:
更改为private async Task DeleteAllTempFiles()
,然后无需等待就可以调用它!
要么
new Thread(() => { DeleteAllTempFiles(); }).Start();
private void DeleteAllTempFiles()
{
try
{
//Get the temp Path
DirectoryInfo tempDir = new DirectoryInfo(Path.GetTempPath());
//Get all matching files
List<FileInfo> tempFiles = tempDir.GetFiles("tmp????.tmp", SearchOption.AllDirectories).ToList();
//Collect all files that fail to delete
List<FileInfo> cannotDelete = new List<FileInfo>();
//Delete Files:
DeleteFiles(tempFiles, out cannotDelete);
//Show what failed (and retry or whatever)
string message = "Cannot delete the following file(s):";
cannotDelete.ForEach(file => message += "{file.FullName}{Environment.NewLine}");
MessageBox.Show(message, "Result");
}
catch (Exception ex)
{
Debug.Fail(ex.Message);
}
}
private void DeleteFiles(List<FileInfo> filesToDelete, out List<FileInfo> failedToDelete)
{
foreach(FileInfo file in filesToDelete)
{
try
{
file.Delete();
}
catch (IOException ioEx)
{
failedToDelete?.Add(file); //<-- Check if failedToDelete != null !!!
//This will always happen.
//Since its not "hard fail" you should log it but keep goin !
//MessageBox.Show($"IO-Exception: {ioEx.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Exception: {ex.Message}");
}
}
}
如果要使用无法删除的文件,可以使用以下方法进行处理: 如何找到使用.NET锁定文件的进程?
要快速检查哪些文件可以锁定,可以使用: OpenedFilesView或Windows Sysinternals Process Explorer
也许您可以尝试设置一些属性...也许可以使用以下方法进行访问:
对不起,图片大小不正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.