问题描述
大家好,
我在C#中有Web应用程序。该应用程序的主要用途是生成报告。应用程序在生成报告时创建临时文件我想从Temp文件夹中删除前100个文件。挑战是我无法删除由于某些其他进程使用文件而导致的文件。请帮帮我
我尝试了什么:
i无法删除由于某些其他进程正在使用文件而导致的文件。请帮帮我
那么为什么要忽略它FileStream并尝试在下一行创建自己的文件?
Dim swWriter As New StreamWriter(f.FullName)
那会失败,因为你刚刚在上一行中打开了独占访问文件!
用以下内容替换两行:
使用swWriter作为StreamWriter = File.Open (f.FullName,FileMode.Open)
...
结束使用
并将代码写入省略号所在的文件内。
使用
块将在完成wi后自动关闭文件它,变量 swWriter
超出范围。关闭使用
块后,您可以删除文件,因为它已经不再使用了。
试一试,看看你能得到多少。
请你在匆匆写入代码之前坐下来思考 - 这将为你节省大量的时间和精力! / BLOCKQUOTE>
Hi All,
I have web application in C#. Main use of that application is generating reports. application creating temp files while generating reports. I want to delete top 100 files from the Temp folder. Challenge is i cannot delete the files due to file being used by some other process. please help me
What I have tried:
i cannot delete the files due to file being used by some other process. please help me
So why do you ignore that FileStream and try to create your own in the next line?
Dim swWriter As New StreamWriter(f.FullName)
That's going to fail, because you have just opened the file for exclusive access in the preceding line!
Replace the two lines with this:
Using swWriter As StreamWriter = File.Open(f.FullName, FileMode.Open) ... End Using
And put your code to write the file inside where the ellipsis is.
The Using
block will automatically close the file when you are finished with it, and the variable swWriter
goes out of scope. After the Using
block closes, you can delete your file, safe in the knowledge that it is no longer in use.
Give that a try, and see how much further you get.
And please, sit down and think before you rush into code - it will save you a huge amount of time and effort!
这篇关于删除时某些其他进程正在使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!