C# Prevent other processes from locking your files/folders
I am temporarily extracting a .zip file to disk and I want to delete all those files later on. During testing this, I had extracted some TortoiseSVN metadata folders in the process. When my application tried to delete them later on, it failed with an UnauthorizedAccessException
.
How can I prevent something like that?
Edit: Here's some code to illustrate the issue a little better:
public class Package : IDisposable {
private bool _disposed;
pub开发者_C百科lic string Filename { get; set; }
public DirectoryInfo RootFolder { get; set; }
public Package( string filename, DirectoryInfo rootFolder ) {
Filename = filename;
RootFolder = rootFolder;
}
public static Package Expand( string packageFileName, DirectoryInfo targetDirectory ) {
FileInfo packageFile = new FileInfo( packageFileName );
string publicKey = Settings.Default.PublicKey;
byte[] publicKeyBytes = Convert.FromBase64String( publicKey );
byte[] packageBytes = File.ReadAllBytes( packageFile.FullName );
byte[] decryptedPackageBytes = Blob.DecryptBlob( packageBytes, publicKeyBytes, false );
// Write result
string outputFolderName = targetDirectory.FullName;
Directory.CreateDirectory( outputFolderName );
ZipFile zipFile = ZipFile.Read( decryptedPackageBytes );
zipFile.ExtractAll( outputFolderName );
Package result = new Package( packageFile.FullName, new DirectoryInfo( outputFolderName ) );
return result;
}
~Package() {
Dispose( false );
}
public void Dispose() {
Dispose( true );
GC.SuppressFinalize( this );
}
private void Dispose( bool disposing ) {
if( _disposed ) {
return;
}
if( disposing ) {
RootFolder.Delete( true );
}
// Dispose unmanaged resources.
_disposed = true;
}
}
I would use Package.Expand in a using block and access the extracted files there (currently I just loop through them and print their names to the console). When the block exits and Dispose is called, I get the exception regarding all-wcprops
. Other, non-svn related files are deleted though.
You you sure you disposed of your handle correctly and that the user the app was running as has the rights to delete it?
I have the same problem with tortiose-Git.
When i have a locking problem i use taskmanager to kill the TGitCache-Process (or in your case the TSVNCache-process)
after a short pause the TGitCache starts again and i can continue tu use tortoise.
You can also think of excluding certain directories from tortois-svn supervision
Even though I'm still interested in an answer to my question, my problem had nothing to do with file locks. UnauthorizedAccessException
in this case simply indicates a read-only file.
How to get around that is discussed here: How do I delete a directory with read-only files in C#?
You can use the CreateFile WIN32 API (via p/invoke) to open a directory handle with ShareMode set to 0, then no other processes will be able to obtain a handle to that directory.
精彩评论