Remove Read-Only Attribute On FOLDER On A Network Share - c#

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

Related

Error while starting a WPF-Application on System-Startup

I have a WPF-Application that I would like to start automatically if I start my Computer.
I have a window where a user can configure some settings for the application, one of the possible configuration options is a checkbox, that allows the user to dis- or enable the application to automatically start on the System-Startup.
This is how I set or delete the value in the Registry, depending on the users choice in the Checkbox:
try
{
var currentAssembly = Assembly.GetExecutingAssembly();
var rkApp = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (settingsViewModel.AutostartEnabled)
{
rkApp.SetValue(currentAssembly.GetName().Name, currentAssembly.Location);
}
else
{
rkApp.DeleteValue(currentAssembly.GetName().Name, false);
}
}
catch (Exception exception)
{
}
My Problem is, that even though the Application gets registered and can also be seen in the Autostart-Section within the Task-Manager, that I get the following error every time I restart my computer to check if the Appliction is started:
"You are attempting to open a file of type Application extension (.dll)"
So what am I doing wrong? Is there any way to avoid this error or to fix it? I already tried adding an application manifest file to my project to always start my Application as an Administrator. But that didn't seem to work either.
I'd appreciate any help.
Try to use System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName instead of currentAssembly.Location.
This should give you the path of the running executable. Assembly.GetEntryAssembly does not.

Outlook.Interop - Checking if a folder is hidden

I have an odd problem. I have an application that allows a user to select folders from their Outlook mailboxes/stores, and it's supposed to skip over any folders that are hidden.
To accomplish this, I perform the following check on the folder:
try
{
if (folder.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x10F4000B"))
{
// Yes, it's a hidden folder
return true;
}
}
catch (System.Runtime.InteropServices.COMException comex)
{
// If the hidden property doesn't exist at all, we'll get a COM exception
// here, which is fine.
return false;
}
catch (Exception)
{
// Some other failure
throw;
}
Now, on my test machine, this works perfectly fine. I use MFCMAPI to toggle on/off the hidden attribute, and the application responds appropriately.
On another remote user's machine, ALL of their folders are showing up, even the normally-hidden ones like Quick Step Settings.
I turned up the logging and in the COMException catch() block, I end up seeing things like this:
Checking to see if Quick Step Settings is hidden: NOT HIDDEN
COMException: The property "http://schemas.microsoft.com/mapi/proptag/0x10F4000B" is unknown or cannot be found.
But I walked the user through examining that folder's properties via MFCMAPI and I took screenshots that show that the folder DOES have that hidden flag set to true. So I'm not sure why the application can't see that property...?
The user does make use of mailboxes that are online-only mailbox stores / shared mailboxes, so I'm wondering if there's maybe a different namespace for the property or something under certain circumstances? Can anyone weight in here?

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

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

Visual Studio Command for going to a specific item in source control explorer

Im looking for a way to automatically open Source Control Explorer from inside a plugincode.
So far I managed to open it by executing the command
View.TfsSourceControlExplorer
However, this does not seem to accept any arguments.
My goal here is to do something like this:
destination = "$/dev/framework/someFolder";
_dteObject.ExecuteCommand("View.TfsSourceControlExplorer", destination);
Which will them show me Source Control Explorer in the specified destination.
To anwser CSharpie's comment :
Also there seems to be a bug, if you call navigate to a file of the same directory as the explorer currently is in, everything will disappear.
I had the same problem, got two ways of solving this :
Truncate the filename from the path to only Navigate to folders.
Navigate to root first ("$/"), then navigate to the file you want.
Both works fine in VS2013.
And thanks for the "Application.DoEvent()" fix when the SourceControlExplorer's not opened.
Use the following code to show Source Control Explorer in the specified destination:
public void SelectFolder(string path)
{
dte.ExecuteCommand("View.TfsSourceControlExplorer");
Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExplorerExt explorer =
GetSourceControlExplorer();
if (explorer != null)
explorer.Navigate(path);
}
private Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExplorerExt GetSourceControlExplorer()
{
Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt versionControl =
dte.GetObject("Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt") as
Microsoft.VisualStudio.TeamFoundation.VersionControl.VersionControlExt;
if (versionControl == null)
return null;
return versionControl.Explorer;
}
I believe this is not possible. The source explorer detects the team project and drops you at the root of the team project node. $/myproject/ ..
Happy to be proven wrong on this one...

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

Categories