How to remove windows user account folder using C#? - c#

I have application which creates some windows user accounts, on uninstallation I remove the Windows User Account, but the folder for that user remains there (For example C:\Documents and Settings\UserName\"
How can I remove that folder using C#?
Thanks,

Something along the lines of this?
DirectoryInfo dir = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
dir = dir.Parent.Parent.Parent;
DirectoryInfo[] userDirs = dir.GetDirectories(userName);
foreach (DirectoryInfo userDir in userDirs)
{
userDir.Delete(true);
}

Related

Why do I get message "Access to the path 'bootmgr' is denied " when trying to clear the contents of a directory

Using Windows 10 Home (20H2) on HP Spectre
I am trying to use the following code to clear the contents of a directory
public int clearDirectory(string path)
{
DirectoryInfo targetDir = new DirectoryInfo(path);
foreach (FileInfo file in targetDir.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in targetDir.GetDirectories())
{
dir.Delete(true);
}
return 0;
}
The target directory is on a USB SanDisk which has in its root dir one directory (which has a number of subdirectories) which I created and the following SanDisk files
SanDiskMemoryZone_AppInstaller.apk
SanDiskMemoryZone_QuickStartGuide.pdf
I replaced the path to the USB drive with a path to a directory on my C drive and that worked fine.
How does the bootmgr get involved in this?
In Windows you can declare for each drive if it is bootable or not.
The bootable partition in Windows is a hidden drive called system partition (and that‘s also the reason why no error was shown when you tried to delete the C:-drive)
Your SAN-drive seems to be using a file system which has a hidden folder with ACL only for the system account.
That‘s why you get this error. You have no access right to delete the file/folder.
One solution:
change your code s.t. It only selects files without a leading dot, like with regex: ^\.
If this still doesn’t fix your error then you should try use an elevated process (with adminr rights) to tackle this.
REMARK: before you delete everything from a usb stick, it would be easier to just reformat it then deleting every file.
Maybe look into Diskpart for this.

How to create a folder with c# which is NOT read only?

In my C# forms application, I try to download the data in a directory of my SFTP Server. The data should be stored in a folder which I want to create in "MyDocuments". When the folder is created, I receive an Renci error "failure" because the folder is "read-only".
I tried many ways to create a folder, but I in most ways I used I either got an error, that I don't have the permission to create a folder, or I got an empty file instead of a folder. Right now I got a folder, but unluckily it is read only.
String localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\MyNewFolder\\";
if (Directory.Exists(localPath))
{
Console.WriteLine("Folder already exists");
}
if (!Directory.Exists(localPath))
{
Directory.CreateDirectory(localPath);
DirectoryInfo directory = new DirectoryInfo(localPath);
DirectorySecurity security = directory.GetAccessControl();
}
I expect the folder not to be read only, so that I can safe data in it using my programm. Anyone knows why my code still creates a read only one?
I believe you have to set the following using the DirectorySecurity object:
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\Account", FileSystemRights.FullControl, AccessControlType.Allow));
Then you can create the directory using the following:
DirectoryInfo di = Directory.CreateDirectory(#"directoryToCreatePath", securityRules);
EDITED:
Once you've created the directory using Directory.CreateDirectory(), you can then apply the following to the folder. This will allow the user you've specified to have FullControl of the folder. You can check the permissions for that user via Properties > Security
DirectoryInfo directory = new DirectoryInfo("C:\\CreatedFolder");
DirectorySecurity security = directory.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(#"USERNAME",
FileSystemRights.FullControl,
AccessControlType.Allow));
directory.SetAccessControl(security);

Get the size of readonly file with GetFiles()

Does anybody know why I am not allowed to "read" the size of a file that has the "ReadOnly" bit set? I am running my program as Administrator and I am not attempting to write to the file, I can read properties and file size from File Explorer just fine, even with lower credentials, but my software is not allowed to read from a readonly file and gives me an UnAuthorizedAccess exception. I don't see any logic behind this, anybody who does? Is there a workaround?
private static double DirSize(DirectoryInfo tdir) {
double size = 0;
FileInfo[] files = tdir.GetFiles();
foreach (FileInfo file in files) { size += file.Length; }
DirectoryInfo[] dirs = tdir.GetDirectories();
foreach (DirectoryInfo dir in dirs) { size += DirSize(dir); }
return( size );
}
Edit: the file it's complaining about is a shortcut to a directory that is readonly. Security tab shows no problems on both the directory itself and the shortcut. I guess it's not a big deal cause it's just a shortcut, but I like to understand what's going on and want to count that 1 KB shortcut to my totals.
On Windows, files and directories have different security credentials. You may access a file of a directory easily, but when it comes to a directory itself, you will need to set privileges for the user of your application.
Properties -> Security -> Groups or Usernames
And you must give access to the user of the application which is trying to access the data. (For example IIS user For web applications)

How to know a new folder is created in a particular folder

I am developing a desktop application in C#.
I have programmatically created a folder(say ABC) inside the Main folder in C drive in Windows.
I want to know whether an user has created any new folder(by simply right clicking and creating new folder) inside ABC.
If the user has created a new folder then I need to get the details of that folder like folder name and privacy too.
Thanks in advance!
You can get the subdirectories of a folder (in your example, the folder "ABC") as an array of strings by calling the method GetDirectories:
string[] subdirs = Directory.GetDirectories(#"C:\ABC");
Then, if you'd like, you can iterate through all of them:
foreach (string dir in subdirs)
//dir is a path to a subdirectory
Don't forget the using statement!
using System.IO;
You can use DirectoryInfo to get the list of subfolder
DirectoryInfo dirInfo = new DirectoryInfo(#"c:\ABC");
DirectoryInfo[] subFolders = dirInfo.GetDirectories();
I'm not sure what you mean by privacy...

Unable to Delete Folder Containing Invisible Files

Using Visual Studio 2010 C#. I'm attempting to delete a folder in C:/Windows/MyFolderA where MyFolderA is a folder placed there by my software - Not Microsoft's.
I've used this code to delete the contents of the folder and the folder itself:
foreach (FileInfo tempfi in listOfMSIInstallers)
{
//Delete all Files
DirectoryInfo localDirectoryInfo = new DirectoryInfo(targetDirectory);
FileInfo[] listOfMSIInstallers = localDirectoryInfo.GetFiles("*",SearchOption.AllDirectories);
File.SetAttributes(tempfi.FullName, File.GetAttributes(tempfi.FullName) & ~FileAttributes.ReadOnly); //Remove Read-Only
File.Delete(tempfi.FullName); //Delete File
string parentFolderPath = "C:/Windows/MyFolderA"; //Example string for StackOverflow
//Remove ReadOnly attribute and delete folder
var di = new DirectoryInfo(parentFolderPath);
di.Attributes &= ~FileAttributes.ReadOnly;
Directory.Delete(parentFolderPath);
}
If I attempt to delete the folder I get an exception
"System.IO.IOException: The directory is not empty".
Showing invisible files on my GUI I do not see any. Looking at the folder with a command prompt there appears to be 2 directories: 1 named . and the second named .. (not too familiar with command prompt dir so I don't know if they're temp names or if those are the actual directory names) both at 0 files and 0 bytes.
Debugging through looking at the FileInfo[] object, it doesn't grab the invisible files found from command prompt.
Any ideas how I can delete the files/directory?
Try
Directory.Delete(parentFolderPath, true);

Categories