Reputation: 22307
I have the following C# code that creates a folder:
if (!Directory.Exists(strCreatePath))
{
Directory.CreateDirectory(strCreatePath);
}
It works, except if I have a folder as such: C:\\Users\\UserName\\Desktop
the Directory.Exists
returns false
, which is not true, but then Directory.CreateDirectory
throws an exception: Access to the path 'C:\\Users\\UserName\\Desktop' is denied.
.
Any idea how to prevent that apart from catching such exception, which I prefer to avoid?
Upvotes: 0
Views: 160
Reputation: 22307
Thank you, everyone. Here's how I was able to handle it without throwing unnecessary exceptions:
[DllImportAttribute("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CreateDirectory(string lpPathName, IntPtr lpSecurityAttributes);
void createFolder(string strCreatePath)
{
if (!CreateDirectory(strCreate, IntPtr.Zero))
{
int nOSError = Marshal.GetLastWin32Error();
if (nOSError != 183) //ERROR_ALREADY_EXISTS
{
//Error
throw new System.ComponentModel.Win32Exception(nOSError);
}
}
}
Upvotes: 0
Reputation: 460238
You should check first if the directory is ReadOnly
or not:
bool isReadOnly = ((File.GetAttributes(strCreatePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
if(!isReadOnly)
{
try
{
Directory.CreateDirectory(strCreatePath);
} catch (System.UnauthorizedAccessException unauthEx)
{
// still the same eception ?!
Console.Write(unauthEx.ToString());
}
catch (System.IO.IOException ex)
{
Console.Write(ex.ToString());
}
}
Upvotes: 1
Reputation: 44916
If you do not have at a minimum read-only permission to the directory, the Exists method will return false.
So the behavior you are seeing is expected. This is a legitimate exception that can happen even if you do check for permissions, so your best bet is to simply handle the exception.
Upvotes: 1