How to rename a folder in c# which is currently opened by windows explorer

后端 未结 3 1152
臣服心动
臣服心动 2021-02-13 18:41

When renaming a folder in C#, System.IO.Directory.Move throws System.IO.IOException (message \"access denied\") if that folder or any subfolder is curr

3条回答
  •  后悔当初
    2021-02-13 19:08

    So I'm answering my own question after some further reasearch..

    The folder can be renamed using SHFileOperation() as shown here: https://msdn.microsoft.com/en-us/library/windows/desktop/bb776887%28v=vs.85%29.aspx (whether this uses the 'magic' mentioned by Wouter or not. ;-)

    But if there is a windows/.Net API such as System.IO.Directory.Move, WTF do I need to use the Shell? Not talking about performance ...

    Anyway, using SHFileOperation() is a pain in the a.. using C# since you need to declare all this p-invoke stuff. And in this particular case you need to use different structs for 32 and 64-bit windows, since the packing is different (see http://www.pinvoke.net/default.aspx/shell32.shfileoperation). This is very cumbersome, as usually I'd specify AnyCPU as target. At this point you either need to branch at runtime (very bad indeed), depending whether you are a 64 or 32 bit process, or you build differently for two different targets, which is quite a big impact just to work around the silly explorer.

    Regards

提交回复
热议问题