OpenFileDialog() locks the folder
I use OpenFileDialog()
in my Silverlight application. When I select a file using ShowDialog()
it simply locks the file until I close my application.
I am not able to rename or delete the folder when the application is running (silverlight 开发者_如何学Goapplication in browser)
If I try to select any other file in any another folder, I am able to rename the previous folder. It seems it is releasing the handle.
My goal: I want to rename/delete the folder in filesystem (manually) once I finished uploading.
I know it is not possible to point OpenFileDialog()
to some other folder from code. Any pointers?
Btw, this is the windows error message:
The action can't be completed because the folder is open in another program. Close the folder and try again.
I had the same problem. The follow fixed it
Stream fileStream = openFileDialog1.OpenFile();
if (fileStream != null)
{
...
fileStream.Close();
}
By closing the stream my problem went away... :P
using(var fileStream = openFileDialog1.OpenFile())
{
// do your stuff
}
this will close the stream and fix your problem.
I know this is a very old thread, but I've experienced the same problem and found some odd behavior in the OpenFileDialog.
The problem is not that the FileDialog isn't disposed correctly or that it's not releasing the resources. The problem is that the FileDialog changes the current directory to the directory the user chooses.
This won't happen in every scenario but I've managed to reproduce the error using the ShowHelp property (using .NET Framework 4.7):
var before = Directory.GetCurrentDirectory(); // result: The directory the application started from
using (var fileDialog = new OpenFileDialog()
{
ShowHelp = true
})
{
if (fileDialog.ShowDialog() == DialogResult.OK)
{
// do something
}
}
var after = Directory.GetCurrentDirectory(); // result: The directory the user opened the file from
It may not only be the ShowHelp property that does this but this was how I could reproduce it (and it sure seems like a bug to me).
As Vyacheslav writes we can avoid this behavior by setting RestoreDirectory to true.
AFAIK it the way windows file system work - you can't rename folder while having some open file handles inside. Make sure that you release all resources from folder(File.Close() etc.) before trying to rename it.
Having assigned null to all variables holding a reference to OpenFileDialog and any FileInfo references or in code where all that stuff is out of scope, then try this:-
GC.Collect();
Its a very draconian thing to do and I wouldn't normally recommend it. If it doesn't fix your problem get rid of it.
To avoid such behaviour set RestoreDirectory property value to true. Here you can read more: http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.restoredirectory.aspx
精彩评论