zhengchun
zhengchun

Reputation: 1291

System.AccessViolationException exception in C# and shell32.dll

i write a snippet code that deletes a specified directory in SHFileOperation method.

The SHFileOperation class from a pinvoke.net

the flowing is my test code:

 var interop = new InteropSHFileOperation();
 interop.wFunc = InteropSHFileOperation.FO_Func.FO_DELETE;
 interop.pFrom = path;
 interop.fFlags.FOF_SILENT = true;
 interop.fFlags.FOF_NOERRORUI = true;
 interop.fFlags.FOF_NOCONFIRMATION = true;
 return interop.Execute();          

the above code can worked in my computer(win7,32-bit,.net 4.0),

but when running above code to my other computer(win 2008,64-bit,.net 4.0),i get the flowing error(from windows event viewer):

Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
   at Shopbots.IO.InteropSHFileOperation.SHFileOperation(SHFILEOPSTRUCT ByRef)
   at Shopbots.IO.InteropSHFileOperation.SHFileOperation(SHFILEOPSTRUCT ByRef)
   at Shopbots.IO.InteropSHFileOperation.Execute()

and from windows exceton dialog

event name : APPCRASH
Fault Module Name:  shell32.dll
Fault Module Version:   6.0.6002.18646
Fault Module Timestamp: 4fd23d65
Exception Code: c0000005

[update 2]

according "Don't declare a value for the Pack size. If you omit it, the correct value is used when marshaling and a single SHFILEOPSTRUCT can be used for both 32-bit and 64-bit operation." from a other article:http://www.pinvoke.net/default.aspx/Structures/SHFILEOPSTRUCT.html:

change a SHFILEOPSTRUCT declare that work 32-bit and 64-bit windows operator system(because the InteropSHFileOperation class from pinvoke site that declare a SHFILEOPSTRUCT structure for 32-bit operator system)

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
struct SHFILEOPSTRUCT
{
  ....
}

Upvotes: 0

Views: 967

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

The most common failure mode for SHFileOperation is that the paths need to be double null-terminated. I suspect that you have forgotten to do that and if you do so an access violation is one possible outcome.

As for packing of the struct, it's a standard Win32 struct. It's not packed, it is aligned. Remove the Pack parameter from the StructLayout attribute.

I cannot understand why you would not call FileSystem.DeleteDirectory.

Upvotes: 1

Related Questions