Create a folder without read-only using c# [duplicate] - c#

I was successfully able to remove read only attribute on a file using the following code snippet:
In main.cs
FileSystemInfo[] sqlParentFileSystemInfo = dirInfo.GetFileSystemInfos();
foreach (var childFolderOrFile in sqlParentFileSystemInfo)
{
RemoveReadOnlyFlag(childFolderOrFile);
}
private static void RemoveReadOnlyFlag(FileSystemInfo fileSystemInfo)
{
fileSystemInfo.Attributes = FileAttributes.Normal;
var di = fileSystemInfo as DirectoryInfo;
if (di != null)
{
foreach (var dirInfo in di.GetFileSystemInfos())
RemoveReadOnlyFlag(dirInfo);
}
}
Unfortunately, this doesn't work on the folders. After running the code, when I go to the folder, right click and do properties, here's what I see:
The read only flag is still checked although it removed it from files underneath it. This causes a process to fail deleting this folder. When I manually remove the flag and rerun the process (a bat file), it's able to delete the file (so I know this is not an issue with the bat file)
How do I remove this flag in C#?

You could also do something like the following to recursively clear readonly (and archive, etc.) for all directories and files within a specified parent directory:
private void ClearReadOnly(DirectoryInfo parentDirectory)
{
if(parentDirectory != null)
{
parentDirectory.Attributes = FileAttributes.Normal;
foreach (FileInfo fi in parentDirectory.GetFiles())
{
fi.Attributes = FileAttributes.Normal;
}
foreach (DirectoryInfo di in parentDirectory.GetDirectories())
{
ClearReadOnly(di);
}
}
}
You can therefore call this like so:
public void Main()
{
DirectoryInfo parentDirectoryInfo = new DirectoryInfo(#"c:\test");
ClearReadOnly(parentDirectoryInfo);
}

Try DirectoryInfo instead of FileInfo
DirectoryInfo di = new DirectoryInfo(#"c:\temp\content");
di.Attributes = FileAttributes.Normal;
To clean up attrbutes on files-
foreach (string fileName in System.IO.Directory.GetFiles(#"c:\temp\content"))
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
fileInfo.Attributes = FileAttributes.Normal;
}

The dialog just works in a fairly bizarre way. It always shows up the way you see it in your screen shot, whatever the state of the ReadOnly attribute. The checkbox is in the 'indetermined' state. You have to click it and either clear or check it to make it perform its action. And in spite of the prompt text (but not the hint next to the checkbox), it only changes the ReadOnly attribute on the files in the directory, not the directory itself.
Use the attrib command line command to see what is really going on. In all likelihood, your code fails because the directory contains files that have their ReadOnly attribute set. You'll have to iterate them.

The read-only flag on directories in Windows is actually a misnomer. The folder does not use the read-only flag. The issue is going to be with the customization. The flag is used by Windows to identify that there are customizations on the folder.
This is an old post, with an issue that is sunsetting, but, figured people might still run into it, as it is pretty annoying when you hit it.
Microsoft's Explanation

IEnumerable / Lambda solution for recursively removing readonly attribute from directories and files:
new DirectoryInfo(#"some\test\path").GetDirectories("*", SearchOption.AllDirectories).ToList().ForEach(
di => {
di.Attributes &= ~FileAttributes.ReadOnly;
di.GetFiles("*", SearchOption.TopDirectoryOnly).ToList().ForEach(fi => fi.IsReadOnly = false);
}
);

Set the Attributes property on the original dirInfo:
dirInfo.Attributes = FileAttributes.Normal;
FileSystemInfo[] sqlParentFileSystemInfo = dirInfo.GetFileSystemInfos();
foreach (var childFolderOrFile in sqlParentFileSystemInfo)
{
RemoveReadOnlyFlag(childFolderOrFile);
}

Just in case any one happens across this later...
ALL of the other answers posted before mine are either wrong or use unnecessary recursion.
First of all the "Read Only" check box in the property dialog of windows always has the tri-state marker for folders. This is because the folder itself is not read only but the files inside can be.
If you want to set/unset read only flag for ALL files. you can do it simply as follows:
void SetReadOnlyFlagForAllFiles(DirectoryInfo directory, bool isReadOnly)
{
// Iterate over ALL files using "*" wildcard and choosing to search all directories.
foreach(FileInfo File in directory.GetFiles("*", SearchOption.All.Directories))
{
// Set flag.
File.IsReadOnly = isReadOnly;
}
}

I see that #DotnetDude said in comments that solutions of guys don't work. To my mind it is happens because guys don't mentioned that need to use File.SetAttributes method to apply new attributes.

This may or may not be directly related, but the root issue in your case may be caused by the underlying files. For example, I ran into this issue trying to delete a directory:
System.IO.Directory.Delete(someDirectory, true)
This results in "Access to the path 'blah' is denied". To resolve this underlying problem, I removed the read-only attribute on sub-files and was then able to remove the parent directory. In my case, I was using powershell, so you can use the .NET equivalent.
dir -r $PrePackageDirectory |% {if ($_.PSIsContainer -ne $true){$_.IsReadOnly = $false}}

Shell("net share sharefolder=c:\sharefolder/GRANT:Everyone,FULL")
Shell("net share sharefolder= c:\sharefolder/G:Everyone:F /SPEC B")
Shell("Icacls C:\sharefolder/grant Everyone:F /inheritance:e /T")
Shell("attrib -r +s C:\\sharefolder\*.* /s /d", AppWinStyle.Hide)
this code is working for me.. to share a folder to every one with read and write permission

Related

How to find out if a directory itself is ReadOnly instead of underlying files

The reason why I'm asking this is because .NET sees a folder as ReadOnly if any of the underlying files or folders are ReadOnly. Therefor this code:
if (!Properties.Settings.Default.searchReadOnly &&
(diPath.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
writeable = false;
is always going to set writeable to false.
This is a problem if you need to know if the root folder is ReadOnly.
The My Docments folder is not ReadOnly, but this is what's shown in the properties window:
Any help would be appreciated.
EDIT
I tried to approach you suggested, but Documents still appears to have the ReadOnly flag set.
if (!Properties.Settings.Default.searchReadOnly &&
diPath.Attributes.HasFlag(FileAttributes.ReadOnly)) // == true
searchable = false;
How is this possible? What user is executing the code? I assume the actively logged in user? Again, assuming because I can write to the Documents folder, it can't have the ReadOnly flag set.
this should help
use the System.IO.DirectoryInfo class:
var di = new DirectoryInfo(folderName);
if(di.Exists())
{
if (di.Attributes.HasFlag(FileAttributes.ReadOnly))
{
//IsReadOnly...
}
}
But
This state does not mean read only it's mean null state which means that the state has never changed and it's the default one.
this state means read only
Update
if you have some sub folders that are marked read-only your root folder will be flagged read-only.
So try this check and apply as read-only to your folder than uncheck and apply and you will see that is no more marked as read-only
I found a solution.
var writePermissionSet = new PermissionSet(PermissionState.None);
writePermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write, path));
if (!Properties.Settings.Default.searchReadOnly &&
!writePermissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
//diPath.Attributes.HasFlag(FileAttributes.ReadOnly))
searchable = false;
This doens't really confirm the ReadOnly flag for the directory, but it does assure me that the user does not have Write permissions in this directory. It's kinda the ReadOnly I've been looking for :D

Get rights on folder

I'm trying to get right for a folder. The purpose is to create a file inside this folder when i ask my program to create this file. I tried almost everything and it still don't work.
try
{
DirectorySecurity ds = Directory.GetAccessControl(path);
foreach (FileSystemAccessRule rule in ds.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)))
{
if ((rule.FileSystemRights & FileSystemRights.CreateFiles) > 0 /*== FileSystemRights.CreateFiles)*/)
return true;
}
}
catch (UnauthorizedAccessException e)
{
return false;
}
return false;
My problem is: The FileSystemAccessRule said that I have the permissions but when I want to create my file, "unauthorizedexception" exception appears.
I tried to use a DirectoryInfo, like that:
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity ds = di.GetAccessControl();
instead of to use the "Directory" object directly. Plus, i was thinking that my problem was concerning the GetAccessRules, so I tried to use the SecurityIdentifier and also NTAccount, both said that I have all the right on this folder (FullControl) whereas at the end, i don't have any right. And of course my path is good, I checked it.
Someone knows another method to get the right on a folder, or if I do something wrong, a bit of help will be a pleasure.
I think the problem with your code is that is does not check on the specific users which have access. GetAccessControl gets a list of ALL users that have any access rule applied to the folder, not just YOU.
There is an excellent answer already here how to do the proper checking: Checking for directory and file write permissions in .NET

Remove Read-Only Attribute On FOLDER On A Network Share

I am having an issue that is really killing me.
I have a directory that when I go to the properties window, shows Read-Only as partially checked (not a full check box, but the box is filled).
So I looked in the directory and I checked all the files, none of them have the read-only attribute. Only the folder has it, and only partially.
I tried the following code:
if (directoryInfo.Exists)
{
try
{
directoryInfo.Attributes &= ~FileAttributes.ReadOnly;
foreach (FileInfo f in directoryInfo.GetFiles())
{
f.IsReadOnly = false;
}
}
catch (Exception e)
{
throw e;
}
}
It still did not work. I can right click on the folder and manually remove the read-only permissions but I need to be able to do this in code. The code executes but does not error.
Anyone have any idea what the issue could be? My only guess is because the folder is on a network share (in the form of \\computer\folder\subfolder), that I might need special rights in order to change permissions on a folder?
Please someone help.
Thanks in advance
readonly on folders is used by Windows internally... if you really need to change it then is some work involved (Registry and changing alot of folders)... see http://support.microsoft.com/kb/256614/en-us
Why do you need to make that change ?
EDIT - some information on Powershell and TFS:
http://codesmartnothard.com/ExecutingPowerShellScriptsOnRemoteMachinesWithTFS2010AndTeamDeploy2010.aspx
http://blogs.msdn.com/b/yao/archive/2011/06/15/tfs-integration-pack-and-scripting-using-powershell.aspx
or try a normal "batch file" (.bat) with "attrib -r" on the folder

Get directory where executed code is located

I know that in the same directory where my code is being executed some files are located. I need to find them and pass to another method:
MyLib.dll
Target1.dll
Target2.dll
Foo(new[] { "..\\..\\Target1.dll", "..\\..\\Target2.dll" });
So I call System.IO.Directory.GetFiles(path, "*.dll"). But now I need to get know the path:
string path = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName)
but is there more short way?
You may try the Environment.CurrentDirectory property. Note that depending on the type of application (Console, WinForms, ASP.NET, Windows Service, ...) and the way it is run this might behave differently.
Environment.CurrentDirectory returns the current directory, not the directory where the executed code is located. If you use Directory.SetCurrentDirectory, or if you start the program using a shortcut where the directory is set this won't be the directory you are looking for.
Stick to your original solution. Hide the implementation (and make it shorter) using a property:
private DirectoryInfo ExecutingFolder
{
get
{
return new DirectoryInfo (
System.IO.Path.GetDirectoryName (
System.Reflection.Assembly.GetExecutingAssembly().Location));
}
}

C# Search for subdirectory (not for files)

Every example I see seems to be for recursively getting files in subdirectories uses files only. What I'm trying to do is search a folder for a particular subdirectory named "xxx" then save that path to a variable so I can use it for other things.
Is this possible without looping through all the directories and comparing by name?
Well
Directory.GetDirectories(root);
will return you an array of the subdirectories.
You can then use Linq to find the one you're interested in:
IEnumerable<string> list = Directory.GetDirectories(root).Where(s => s.Equals("test"));
which isn't a loop in your code, but is still a loop nevertheless. So the ultimate answer is that "no you can't find a folder 'test' without looping".
You could add .SingleOrDefault() to the Linq, but that would depend on what you wanted to do if your "test" folder couldn't be found.
If you change the GetDirectories call to include the SearchOption SearchOption.AllDirectories then it will do the recursion for you as well. This version supports searching - you have to supply a search string - though in .NET Framework it's case sensitive searching. To return all sub directories you pass "*" as the search term.
Obviously in this case the call could return more than one item if there was more than one folder named "test" in your directory tree.
var foldersFound = Directory.GetDirectories(root, "test", SearchOption.AllDirectories)
This will return a string array with all the folders found with the given name. You can change the last parameter so that it only checks top level directories and you can change root to adjust where it is starting from.
First of all, "No, it is not possible without looping through all the directories and comparing by name".
I believe your real question is "Is there an existing API which will handle looping through all the directories and comparing by name for me?"
Yes, there is. It's called Directory.Exists():
var xxxPath = Path.Combine(parentFolder, "xxx");
if (Directory.Exists(xxxPath))
savedPath = xxxPath;
Yes, I believe that the only available solution (short of third party libraries) is a recursive search for the directory via name comparison.
You can use Windows Search which provides api for .Net too. Here is more detailed information: Windows Search 4.0 for Developers
Here is a snippet for searching for a folder using two filters while considering for the UnauthorizedAccessException, it can be refactored to use only one filter:
public static string FindGitPath(string firstFilter, string secondFilter, string initialPath)
{
string gitPath = string.Empty;
foreach (var i in Directory.GetDirectories(initialPath)) {
try {
foreach (var f in Directory.GetDirectories(i, firstFilter, SearchOption.AllDirectories)) {
foreach (var s in Directory.GetDirectories(f)) {
if (s == Path.Combine(f,secondFilter)) {
gitPath = f;
break;
}
}
}
} catch (UnauthorizedAccessException) {
Console.WriteLine("Path is not accessible: {0}", i);
}
}
return gitPath;
}
Usage example:
Console.WriteLine("Retrieved the git database folder as {0}", FindGitPath("database",".git", "c:\\"));

Categories