I am trying to get security information of some files and directories inside a network folder. Unfortunately some files and directories path exceed their character limits 260/248 respectively. I found so many information to use Win32 P/Invoke, use .NET Framework 4.6.2 etc. I was able to use a code by Kim Hamilton to iterate through each files and directories inside whose path exceeds the length limit but I could not use it to get the security information.
Below is my simple C# code containing a path which is above 260 characters. It will throw a Path Too Long Exception. Could you please help me solve it in this scenario.
using System.IO;
using System.Security.AccessControl;
namespace Microsoft.Experimental.IO
{
class Program
{
public static void Main(string[] args)
{
string path = @"\\Domain\UserData\VeryLongPath"; //This is above 260 characters
DirectoryInfo info = new DirectoryInfo(path);
DirectorySecurity security = Directory.GetAccessControl(path);
}
}
}
Accepted answer didn't really work for me although I checked the registry key (it seems to be enabled by default nowadays). The exception thrown was as mentioned: invalid name, invalid parameter (happened on SetAccessControl
in my case). .NET 4.7.2
What helped is the special syntax: \\\\?\\
for local paths or \\\\?\\UNC\\
for network shares.
So for the example in question (server share) it would be something like below:
var security = Directory.GetAccessControl($@"\\?\UNC\{path.TrimStart('\\')}");
I saw in some other posts that installing .NET Framework 4.6.2 does help. As the last resort, I tried it. I had Visual Studio 2015. I installed .NET Framework 4.6.2. It still did not work. Then I installed Visual Studio 2017 and chose .NET Framework 4.6.2 . It did eliminate Path Too Long Exception. But it gave a new exception called Invalid name, Invalid parameter.
One of my colleague suggested me to check the value of registry
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled
It's original value was 0. I set it to 1. And both the Path Too Long and Invalid Name, Invalid parameter exception were gone. I believe this registry key does not exist in computer that does not have .NET Framework 4.6.2.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.