Copy parent folder permissions to child files - c#

So, basically I have an issue where these files are being moved into folders from a couple layers up and the permissions of the child are not being inheritied for some reason. From what I can tell this is the intended function of windows but I need it to work different so I decided to do this:
foreach (string directory in System.IO.Directory.GetDirectories(#"path", "*", SearchOption.TopDirectoryOnly))
{
foreach (string file in System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly))
{
DirectorySecurity DS = System.IO.Directory.GetAccessControl(directory);
FileSecurity FS = new FileSecurity();
System.IO.FileInfo FI = new FileInfo(file);
foreach (FileSystemAccessRule rule in DS.GetAccessRules(true, true, typeof(NTAccount)))
{
FS.AddAccessRule(rule);
}
FI.SetAccessControl(FS);
}
}
However this is generating an error while doing "fs.addaccessrule" saying:
system.argumentexception no flags can be set
I can't figure out how i'm supposed to move the permissions from the parent folder to the child file.

This is the solution I came up with, just creating a new rule based on the rule I want to use and removing the inheritedflags.
foreach (string directory in System.IO.Directory.GetDirectories(#"path", "*", SearchOption.AllDirectories))
{
foreach (string file in System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly))
{
DirectorySecurity DS = System.IO.Directory.GetAccessControl(directory, AccessControlSections.Access);
FileSecurity FS = new FileSecurity();
System.IO.FileInfo FI = new FileInfo(file);
foreach (FileSystemAccessRule rule in DS.GetAccessRules(true, false, typeof(NTAccount)))
{
FileSystemAccessRule nRule = new FileSystemAccessRule(rule.IdentityReference, rule.FileSystemRights, InheritanceFlags.None, rule.PropagationFlags, rule.AccessControlType);
FS.AddAccessRule(nRule);
}
FI.SetAccessControl(FS);
}
}

Related

Copy files and backup the existing + subdirectories

I am trying to make a program to backup files from a particular folder, along with the files within the subfolders of the main folder to another backup folder.
This is part of the code I am trying to accomplish the goal, however I am getting backed up only the files from the main folder, and the subfolders are being copied entirely(all of the files in them).
public static string[] Backup(string sourceDirectory, string targetDirectory, string backupDirectory)
{
DirectoryInfo diBackup = new DirectoryInfo(backupDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
List<string> dups = new List<string>();
string[] fileNamesSource = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories);
string[] fileNamesDest = Directory.GetFiles(targetDirectory, "*", SearchOption.AllDirectories);
List<string> dupNS = new List<string>();
List<string> dupND = new List<string>();
List<string> BCKP = new List<string>();
string replacement = "";
for (int i = 0; i < fileNamesDest.Length; i++)
{
string res = fileNamesDest[i].Replace(targetDirectory, replacement);
dupND.Add(res);
}
foreach (var ns in fileNamesSource)
{
string res = ns.Replace(sourceDirectory, replacement);
dupNS.Add(res);
}
var duplicates = dupND.Intersect(dupNS);
string[] DuplicatesStringArray = duplicates.ToArray();
foreach (var dup in DuplicatesStringArray)
{
string res = targetDirectory + dup;
BCKP.Add(res);
}
string[] ToBeBackedUp = BCKP.ToArray();
Directory.CreateDirectory(diBackup.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in diTarget.GetFiles())
{
if (ToBeBackedUp.Contains(fi.FullName)){
fi.CopyTo(Path.Combine(diBackup.FullName, fi.Name), true);
}
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in diTarget.GetDirectories())
{
if (ToBeBackedUp.Contains(diSourceSubDir.FullName)) {
DirectoryInfo nextTargetSubDir =
diBackup.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
return ToBeBackedUp;
}
Any ideas of how can I copy only the files in the subfolders that exist in the "source" folder?
Also the CopyAll function:
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
Thanks in advance.
You can try this way as
Much easier
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
A simple solution: in your CopyAll method, load the SearchOption.AllDirectories argument to your GetFiles method:
foreach (FileInfo fi in source.GetFiles("*", SearchOption.AllDirectories))
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
You can use Directory.GetFiles along with SearchOption.AllDirectories to extract the files from the sub-folders as well:
Directory.GetFiles(path, *search pattern goes here*, SearchOption.AllDirectories)

Move multiple selected files into specific folder

I have implemented a code like this from which I got the idea somewhere.
public string BrowseFolder()
{
string filePath = string.Empty;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Multiselect = true;
openFileDialog1.Title = "Browse EXCEL File";
openFileDialog1.Filter = "Excel Files (*.xlsx)|*.xlsx";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog1.FileName;
return Path.GetDirectoryName(filePath);
}
return null;
}
public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name.ToString());
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
Ok let's assume that this two methods is in a class. I have easily understood how this codes work. It is copying all the files inside the folder I browse. This is not what I need. What I wanted to achieve is to copy only the selected files (multiple) in my folder.
I've tried to manipulate my code but I still didn't get the right solution. Thanks in advance.
foreach (string file in openFileDialog1.FileNames)
{
FileInfo fInfo = new FileInfo(file);
fInfo.MoveTo(newFilePath);
}
Ref: https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filenames(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.io.fileinfo.moveto(v=vs.110).aspx
You need to get all the files selected from OpenFileDialog like this:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string[] filesSelected = openFileDialog1.FileNames;
}
The code above returns all the files that a user selected from the OpenFileDialog.

Copy the files from folders recursively with wildcard characters (folder path has wildcard characters)

Good day.
I have to copy all the files in folders (including sub folders) to other shared drive location for backup the data. The challenge, which I am facing is folder path with wildcard characters.
For example,
The folder structure is like below
D:/Folder1/Folder11/Folder111
D:/Folder2/Folder222/Folder222222
D:/Folder3/Folder333333/Folder3333333
I am looking for the input format should be "D:/Folder?/Folder*/Folder*". So that it has to loop according to the wildcard character patterns.
Can you please help me.
Regards,
Chandra
You can achive this with a simple RegularExpression. I've created an example which does the job for you.
The RegEx string is quite easy: [A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}
[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}
----- -------- -------- --------
Drive 1x digit 2x digit 3x digit
See the sample at regexr.
EDIT:
//using System.IO;
public void CopyMatching(string drive)
{
try
{
var backuplocation = ""; //the path where you wanna copy your files to
var regex = new Regex(#"[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}");
var directories = new List<string>();
foreach (var directory in Directory.EnumerateDirectories(drive))
{
if (regex.IsMatch(directory))
{
directories.Add(directory);
}
}
foreach (var directory in directories)
{
DirectoryCopy(directory, backuplocation, true);
}
}
catch (Exception)
{
throw;
}
}
And DirectoryCopy:
public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
IEnumerable<string> getMatchingSubDir(string dirPath, string pattern)
{
List<string> matchingFolders = new List<string>();
DirectoryInfo myDir = new DirectoryInfo(dirPath);
foreach (var subDir in myDir.GetDirectories(pattern))
{
matchingFolders.AddRange(getMatchingSubDir(subDir.FullName, pattern));
}
return matchingFolders;
}
Then this call will return you a list of all folders matching your pattern:
getMatchingSubDir("D:\\", "Folder*");

Directory.GetFiles how to access subdirectories? [duplicate]

This question already has answers here:
Get all sub directories that only contain files
(4 answers)
Closed 9 years ago.
How can I get files from sub-directories as well, using this code only gets the job done for files under the directory listed:
DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
Directory.CreateDirectory(folderBrowserDialog1.SelectedPath + "\\Output");
foreach (FileInfo d in selDir.GetFiles())
{
//my code
}
var allFiles = selDir.GetFiles("*.*", SearchOption.AllDirectories);
I usually make a recurring method to do this. Example:
private void getFiles(string directory)
{
string[] files = Directory.GetFiles(directory);
string[] directories = Directory.GetDirectories(directory);
foreach (string file in files)
{
// Code here.
}
foreach (string subDirectory in directories)
{
// Call the same method on each directory.
getFiles(subDirectory);
}
}
You have the DirectoryInfo of your desired folder, so loop over all it's directories, then you can get the files for each.
DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
Directory.CreateDirectory(Path.Combine(folderBrowserDialog1.SelectedPath, "Output"));
foreach (string dir in System.IO.Directory.GetDirectories(selDir.FullName, "*.*", System.IO.SearchOption.AllDirectories))
{
foreach (string file in Directory.GetFiles(dir))
{
//my code
}
}
DirectoryInfo selDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
Directory.CreateDirectory(folderBrowserDialog1.SelectedPath + "\\Output");
string[] files = Directory.GetFiles(selDir.FullName, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
// your code
}

Copying Files Recursively

I found a small snippet for doing a recursive file copy in C#, but am somewhat stumped. I basically need to copy a directory structure to another location, along the lines of this...
Source: C:\data\servers\mc
Target: E:\mc
The code for my copy function as of right now is...
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(baseDir, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(baseDir, targetDir));
}
// Copy each file into it’s new directory.
foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{
Console.WriteLine(#"Copying {0}\{1}", targetDir, Path.GetFileName(file));
if (!CopyFile(file, Path.Combine(targetDir, Path.GetFileName(file)), false))
{
int err = Marshal.GetLastWin32Error();
Console.WriteLine("[ERROR] CopyFile Failed on {0} with code {1}", file, err);
}
}
The issue is that in the second scope, I either:
use Path.GetFileName(file) to get the actual file name without the path but I lose the directory "mc" directory structure or
use "file" without Path.Combine.
Either way I have to do some nasty string work. Is there a good way to do this in C# (my lack of knowledge with the .NET API leads me to over complicating things)
MSDN has a complete sample: How to: copy directories
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", #".\temp", true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName,
bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
A non-recursive replacement for this answer would be:
private static void DirectoryCopy(string sourceBasePath, string destinationBasePath, bool recursive = true)
{
if (!Directory.Exists(sourceBasePath))
throw new DirectoryNotFoundException($"Directory '{sourceBasePath}' not found");
var directoriesToProcess = new Queue<(string sourcePath, string destinationPath)>();
directoriesToProcess.Enqueue((sourcePath: sourceBasePath, destinationPath: destinationBasePath));
while (directoriesToProcess.Any())
{
(string sourcePath, string destinationPath) = directoriesToProcess.Dequeue();
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);
var sourceDirectoryInfo = new DirectoryInfo(sourcePath);
foreach (FileInfo sourceFileInfo in sourceDirectoryInfo.EnumerateFiles())
sourceFileInfo.CopyTo(Path.Combine(destinationPath, sourceFileInfo.Name), true);
if (!recursive)
continue;
foreach (DirectoryInfo sourceSubDirectoryInfo in sourceDirectoryInfo.EnumerateDirectories())
directoriesToProcess.Enqueue((
sourcePath: sourceSubDirectoryInfo.FullName,
destinationPath: Path.Combine(destinationPath, sourceSubDirectoryInfo.Name)));
}
}
instead of
foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{
do something like this
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}

Categories