How to replicate a folder structure - c#

I want to be able to replicate only the folder structure (not the contents) from one location to another in c# 3.5
for example
C:\Some Folder
+ Folder A
+ Sub Folder A
+ Sub Folder B
+ Sub Folder B1
+ Sub Folder B2
+ Sub Folder C
To New Location
C:\Some New folder
+ Folder A
+ Sub Folder Aetc... etc..

Do you mean you want to create the same files, but not the contents within the same structure.
Something like this might work:
public static TotallyNotRecursiveAndCreateDirs(string root, string newRoot)
{
DirectoryInfo rootDir = new DirectoryInfo(Path.GetPathRoot(root));
DirectoryInfo[] dirs = rootDir.GetDirectories("*", SearchOption.AllDirectories);
foreach(DirectoryInfo dir in dirs)
{
Directory.CreateDirectory(dir.FullName.Replace(root, newRoot));
FileInfo[] files = dir.GetFiles("*.*", SearchOption.TopDirectoryOnly);
foreach(FileInfo file in files)
{
File.Create(file.FullName.Replace(root, newRoot));
}
}
}
You might also want to do some exception checking to ensure that the root and the newRoot parameters are valid (ie: rooted, etc...)
If you don't want the files and just the directories, then just remove the second loop.

To copy a folder structure at src to dest:
Create dest.
(Optional) Set permissions on dest to match src.
For each folder name in src, copy the folder structure at src\name to dest\name.

Related

How can I get the name of a sub folder (Thats name will vary) which I need to pass into a hard coded path to run a File.Exists

I need to check if a certain file (a .config file) exist inside a given set of sub folders but I do not know what the name of these Sub folders are (As the Sub folder is named by User preference) However these sub folders will reside only inside a given directory.
How can I get the name of this sub folder to a path where I can use File.Exists to check if the file exist.
if (File.Exists(# "D:\TEST\PROJ\Repo\{lastFolderName}\fileserver.config")) {
MessageBox.Show("File Found");
} else {
MessageBox.Show("File Not Found");
}
you have to try out like this
string path =# "D:\TEST\PROJ\Repo\";
DirectoryInfo directory = new DirectoryInfo(path);
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach(DirectoryInfo folder in subDirectories)
{
string subpath = Path.Combine( # "D:\TEST\PROJ\Repo\", folder.Name);
string[] filePaths = Directory.GetFiles(subpath, "fileserver.config");
if(filePaths.Any())
Console.WriteLine(subpath);
}

How to copy dll file dependency to Temp compilation folder for Azure Function App?

I am working with an azure function app that uses a third-party DLL, that has a dependency on an XML mapping file being present in a folder relative to the current execution. When I publish and run my function on my Azure stack, I run into an exception that the dll cannot load the XML file. I have the XML present in my bin directory with the dll, but Azure appears to be moving the compiled dlls to a temporary folder without the required XML, and proceeds to be looking for the XML relative to that temporary path based on the following exception message:
"Could not find a part of the path 'D:\\local\\Temporary ASP.NET Files\\root\\da2a6178\\25f43073\\assembly\\dl3\\28a13679\\d3614284_4078d301\\Resources\\RepresentationSystem.xml'."
Is there any way I can make sure these additional files are also copied to the temporary folder that Azure is running? Alternatively, can I just force it to run from bin rather than temp?
Update: Unfortunately I am not permitted to share any info on the dll. What I can say is that everything is published to my wwwroot folder, however when outputing some debug info, I can see that the execution is happening from the "Temporary ASP.NET Files" folder. Each dll is copied to its own seperate folder. D:\local\Temporary ASP.NET Files\root\da2a6178\25f43073\assembly\dl3\28a13679\d3614284_4078d301\ThirdParty.dll is that path were the dll in question is, and it lines up with where it expects the xml to be.
While this isn't a true answer to the issue, a workaround for this problem was to have a function in code before the dll functions run, that searches for the dll in question in the Temp ASP.Net folder, and then copies the xml files from a known location to that directory.
// Work Around Begin Here
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// Check if we are in temp dir
if (assemblyFolder.Contains("Temporary ASP.NET Files"))
{
DirectoryInfo dir = new DirectoryInfo(assemblyFolder);
// Go up 2 dirs
DirectoryInfo top = dir.Parent.Parent;
DirectoryInfo[] dirs = top.GetDirectories();
foreach (DirectoryInfo child in dirs)
{
DirectoryInfo[] dirs2 = child.GetDirectories();
foreach (DirectoryInfo child2 in dirs2)
{
// Find out if this is the Rep
if (File.Exists(child2.FullName + "\\ThirdParty.Representation.dll"))
{
// Look to see if resource folder is there
if (!Directory.Exists(child2.FullName + "\\Resources"))
{
child2.CreateSubdirectory("Resources");
}
DirectoryInfo resDir = new DirectoryInfo(child2.FullName + "\\Resources");
if (File.Exists(resourceDir + "RepresentationSystem.xml"))
{
if(!File.Exists(resDir.FullName + "\\RepresentationSystem.xml"))
{
File.Copy(resourceDir + "RepresentationSystem.xml", resDir.FullName + "\\RepresentationSystem.xml");
}
}
if (File.Exists(resourceDir + "UnitSystem.xml"))
{
if (!File.Exists(resDir.FullName + "\\UnitSystem.xml"))
{
File.Copy(resourceDir + "UnitSystem.xml", resDir.FullName + "\\UnitSystem.xml");
}
}
}
}
}
}
Thank you DoubleHolo for this workaround. It run fine.
I have changed the code adding only Path.Combine to simplify the code.
private void CopyResourcesToTemporaryFolder()
{
// Work Around Begin Here
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string resourceDir = Path.Combine(FileUtils.WebProjectFolder, "Resources");
// Check if we are in temp dir
if (assemblyFolder.Contains("Temporary ASP.NET Files"))
{
DirectoryInfo dir = new DirectoryInfo(assemblyFolder);
// Go up 2 dirs
DirectoryInfo top = dir.Parent.Parent;
DirectoryInfo[] dirs = top.GetDirectories();
foreach (DirectoryInfo child in dirs)
{
DirectoryInfo[] dirs2 = child.GetDirectories();
foreach (DirectoryInfo child2 in dirs2)
{
// Find out if this is the Rep
if (File.Exists(Path.Combine(child2.FullName, "AgGateway.ADAPT.Representation.DLL")))
{
// Look to see if resource folder is there
if (!Directory.Exists(Path.Combine(child2.FullName, "Resources")))
{
child2.CreateSubdirectory("Resources");
}
DirectoryInfo resDir = new DirectoryInfo(Path.Combine(child2.FullName, "Resources"));
if (File.Exists(Path.Combine(resourceDir, "RepresentationSystem.xml")))
{
if (!File.Exists(Path.Combine(resDir.FullName, "RepresentationSystem.xml")))
{
File.Copy(Path.Combine(resourceDir, "RepresentationSystem.xml"), Path.Combine(resDir.FullName, "RepresentationSystem.xml"));
}
}
if (File.Exists(Path.Combine(resourceDir, "UnitSystem.xml")))
{
if (!File.Exists(Path.Combine(resDir.FullName, "UnitSystem.xml")))
{
File.Copy(Path.Combine(resourceDir, "UnitSystem.xml"), Path.Combine(resDir.FullName, "UnitSystem.xml"));
}
}
}
}
}
}
}

What is the best way to move a folder inside itself?

Assuming I want to move a folder inside itself, with its former contents empty but for the new folder, how would I best go about it using code. Normally, in explorer, you would do this by cutting the content of the folder and placing it in a new folder created inside the original folder.
i.e.
Original Path: C:\Users\Previous
New Path: C:\Users\Previous\Previous
cerate the temp folder : c:\user\temp
move the directory with Move from c:\user\previous to : c:\user\temp
rename the temp folder with Move from c:\user\temp to c:\user\previous
As you wanted to move folder and its contents to a sub folder with the same name, you could do as follows:
private void button1_Click(object sender, EventArgs e)
{
CopyContentsToSubFolderWithSameName(#"C:\Users\Previous");
}
private void CopyContentsToSubFolderWithSameName(string path)
{
DirectoryInfo currDir = new DirectoryInfo(path);
DirectoryInfo subDir =
Directory.CreateDirectory(Path.Combine(currDir.FullName, currDir.Name));
IEnumerable<DirectoryInfo> parentFolders =
subDir.Parent.EnumerateDirectories();
// Copy files in the current directory to the destination directory
foreach (FileInfo file in currDir.GetFiles())
{
file.MoveTo(Path.Combine(subDir.FullName, file.Name));
}
// Copy directories (including files) in the current directory
// to the destination directory
foreach (DirectoryInfo dir in parentFolders)
{
if (dir.Name != subDir.Name)
{
dir.MoveTo(Path.Combine(subDir.FullName, dir.Name));
}
}
}

Check for Sub directory in C#

I am storing the files extracted from a rar/zip file in a folder.
After that I am storing the files inside that folder to a database. The problem is it stores only the files in the folder not the sub directories and its files.
How to find if the folder has any sub directories.
I am using the code below
Directory.CreateDirectory(StorageRoot + path + New_folder);
decom(StorageRoot + path + New_folder, StorageRoot + path + file.FileName);
foreach (var access_file in Directory.GetFiles(StorageRoot + path + New_folder))
{
string new_name=System.IO.Path.GetFileName(access_file);
FileInfo f = new FileInfo(StorageRoot + path + New_folder+ "/" + new_name);
int new_size = unchecked((int)f.Length);
string new_path = path + New_folder;
statuses.Add(new FilesStatus(new_name, new_size, new_path, StorageRoot, data));
}
How to get the list of files and directories in a folder. and save them in db?
To get the files and directories in a folder you can use Directory.GetFiles() and Directory.GetDirectories()
Use recursion or Queue to recursively traverse directories.
Example with recursion:
void Traverse(string directory)
{
foreach(var dir in Directories.GetDirectories(directory))
{
Traverse(directory);
}
// Your code here
}
This may helps:
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo("YOUR PATH");
//List of directories
var result = info.GetDirectories().Select(i => i.FullName);
You can use GetDirectories to get sub folder DirectoryInfo's and iterate through them untill Getdirectories returns nothing.
You can use Directory.GetFileSystemEntries() to get a list of both files and directories.
http://msdn.microsoft.com/en-us/library/system.io.directory.getfilesystementries.aspx

Searching through a file structure to count items in a subfolder

I am having an issue with trying to make a list by searching through a file structure. Was trying to make a basic c# console program that would just run and do this.
My structure is organize like the following.
My Network \
X1 \
Users \
(many many user folders) \
Search for a specific sub folder \
make a list in a text file of any folders within this sub folder
So i have to be able to search every user folder and then check for a folder (this will be the same every time) Then make a list of the found folders within that sub folder with the following format
username (name of the user folder) >> Name of folder within the specific folder.
its been a terribly long time since i have had to try anything with searching within a file structure so blanking on this terribly.
**************** EDIT!!!!!
Thanks for the info and links. Working on this now but wondering if this makes sense and would work. Don't want to just test it before i make sure it looks like something that wouldn't just screw up.
TextWriter outputText = new StreamWriter(#"C:\FileList.txt", true);
outputText.WriteLine("Starting scan through user folder");
string path = #"\\X1\users";
string subFolder = "^^ DO NOT USE - MY DOCS - BACKUP ^^";
string [] user_folders = Directory.GetDirectories(path);
foreach (var folder in user_folders)
{
string checkDirectory = folder + "\\" + subFolder;
if (Directory.Exists(checkDirectory) == true)
{
string [] inner_folders = Directory.GetDirectories(checkDirectory);
foreach (var folder2 in inner_folders)
{
outputText.WriteLine(folder2);
}
}
}
outputText.WriteLine("Finishing scan through user folder");
outputText.Close();
Fixed and working!!!! had to change the string [] lines, to make it .GetDirectories instead of .GetFiles!!
As Bali C mentioned, the Directory class will be your friend on this one. The following examples should get you started.
From: http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/3ea19b83-b831-4f30-9377-bc1588b94d23/
//Obviously you'll need to define the correct path.
string path = #"My Network\X1\Users\(many many user folders)\Search for a specific sub folder \";
// Will Retrieve count of all files in directry and sub directries
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;
// Will Retrieve count of all files in directry but not sub directries
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length;
// Will Retrieve count of files .txt extensions in directry and sub directries
int fileCount = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories).Length;
If you need to search the /Users/ folder for certain people, or certain conditions you could do the following:
string path = #"PATH_TO_USERS_DIRECTORY";
string [] user_folders = Directory.GetFiles(path);
foreach(var folder in user_folders)
{
if folder == "MyFolder";
Process(folder); //Search the directory here.
}
Try the following implementation. This will just write to the console:
const string root = "<<your root path>>";
const string directoryToLookFor = "<<the folder name you are looking for>>";
foreach (var directory in Directory.EnumerateDirectories(root, "*.*", SearchOption.TopDirectoryOnly))
{
var foundDirectory = Directory.EnumerateDirectories(directory, directoryToLookFor, SearchOption.TopDirectoryOnly).FirstOrDefault();
if (!String.IsNullOrEmpty(foundDirectory))
{
var filesInside = Directory.GetFiles(foundDirectory);
foreach (var file in filesInside)
{
Console.WriteLine(file);
}
}
}
Or you could just do:
foreach (var foundDirectory in Directory.EnumerateDirectories(root, directoryToLookFor, SearchOption.AllDirectories))
{
var filesInside = Directory.GetFiles(foundDirectory);
foreach (var file in filesInside)
{
Console.WriteLine(file);
}
}
Which would search within all subdirectories without you having to iterate over the users' folders.

Categories