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
Related
I need a library of vector files, where the same files have to be used every time. I want to load them from a folder and have the option to store new ones.
I tried having a library folder inside the WPF project that contains the files:
Solution/Project/Library/file1.dxf
I load them like this:
string currentDir = Directory.GetCurrentDirectory();
var cutOff = currentDir.LastIndexOf(#"\bin\");
var folder = currentDir.Substring(0, cutOff) + #"\Library\";
string[] filePaths = Directory.GetFiles(folder, "*.dxf");
This worked when running on the PC the project was buid, but the program crashes when the .exe is run on another PC. How do I fix this or is there a better approach to this?
Create a subfolder under Environment.SpecialFolder.ApplicationData, read the files in the library folder if it exists. If not create it and save the existing library files to it (here from resources):
string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appFolder + #"\MyAppLibrary\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// Add existing files to that folder
var rm = Properties.Resources.ResourceManager;
var resSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var res in resSet)
{
var entry = ((DictionaryEntry)res);
var name = (string)entry.Key;
var file = (byte[])rm.GetObject(name);
var filePath = path + name + ".dxf";
File.WriteAllBytes(filePath, file);
}
}
// Load all files from the library folder
string[] filePaths = Directory.GetFiles(path, "*.dxf");
Thanks Jonathan Alfaro and Clemens!
I have an ASP.NET MVC application, hosted on IIS 8, windows server 2012 and I upload some files to a temporary directory. After doing some other work, all these files are moved to a concrete directory. My question is why doesn't Directory.Move work while FileInfo.CopyTo works.
Directory.Move fails with
"Access to the path 'serverPath...' is denied."
Code I'm using to move entire directory:
var pathFrom = Server.MapPath("~/Uploads/Objects/" + tempFolderName); //tempFolderName is a random generated GUID.
var pathTo = Server.MapPath("~/Uploads/Objects/" + ObjectId); //ObjectId is an integer
if (Directory.Exists(pathFrom))
{
Directory.Move(pathFrom, pathTo);
}
To create a temporary directory I'm simply calling: Directory.CreateDirectory(path) which works and creates the temporary directory, and files are saved inside it.
Method I use to copy files, one by one, which works:
public static void DirectoryCopy(string strSource, string Copy_dest)
{
DirectoryInfo dirInfo = new DirectoryInfo(strSource);
DirectoryInfo[] directories = dirInfo.GetDirectories();
FileInfo[] files = dirInfo.GetFiles();
foreach (DirectoryInfo tempdir in directories)
{
Console.WriteLine(strSource + "/" + tempdir);
Directory.CreateDirectory(Copy_dest + "/" + tempdir.Name);// creating the Directory
var ext = System.IO.Path.GetExtension(tempdir.Name);
if (System.IO.Path.HasExtension(ext))
{
foreach (FileInfo tempfile in files)
{
tempfile.CopyTo(Path.Combine(strSource + "/" + tempfile.Name, Copy_dest + "/" + tempfile.Name));
}
}
DirectoryCopy(strSource + "/" + tempdir.Name, Copy_dest + "/" + tempdir.Name);
}
FileInfo[] files1 = dirInfo.GetFiles();
foreach (FileInfo tempfile in files1)
{
tempfile.CopyTo(Path.Combine(Copy_dest, tempfile.Name));
}
}
What I tried to make Directory.Move work:
Checked to see if directory pathTo doesn't exist
Checked to see if IIS has required permissions: IISAppPool/DefaultAppPool has full access to the Uploads folder.
Tried to check with Process monitor if any other error comes up but it seems that this doesn't even get logged.
Closed every explorer.
Can anyone explain why Directory.Move doesn't work (with the access deny error) while moving the files one by one works?
Does Directory.Move require more privileges than just copying files 1 by 1?
Please be aware that the application is not under wwwroot... but on other drive.
Pages I already read:
Why am I still getting "Access to the path 'C:\...\...' is denied" even after granting IIS_IUSRS write permission on the directory?
Access to path denied on IIS
IOException access denied when Directory.Move subfolder and parent folder
EDIT
After copying the files using FileInfo.Copy I delete the tempFolder with Directory.Delete(pathFrom, true); which also works.
I am moving files from source folder to destination folder. Before moving files, I am checking that directory exists or not which is working fine. The issue is with my second check where I want to make sure that folder is not empty before moving files but it is not giving me correct result.
public void MoveFilesFromTempToSourceTbl()
{
//Moving all files from temp folder to orig folder.
string sourceFolder = (twitterDO.Path + "\\" + msgDate.Year.ToString() + "\\" + msgDate.Month.ToString() + "\\" + msgDate.Day.ToString() + "_Temp").Replace("\\", #"\");
string destinationFolder = (twitterDO.Path + "\\" + msgDate.Year.ToString() + "\\" + msgDate.Month.ToString() + "\\" + msgDate.Day.ToString()).Replace("\\", #"\");
string pattern = "*.txt";
if (Directory.Exists(sourceFolder))
{
if (File.Exists(pattern))
{
foreach (var file in new DirectoryInfo(sourceFolder).GetFiles(pattern))
{
file.MoveTo(Path.Combine(destinationFolder, file.Name));
}
}
if (Directory.GetFiles(sourceFolder).Length == 0) //Before deleting make sure that Temp folder is empty.
Directory.Delete(sourceFolder, true); // Delete Temp folder after moving all the contents.
}
}
I know I am making some small mistake but not sure what it is. Following is the screenshot of the result which I got in immediate window.
http://imgur.com/FZvo9cj
There's a bit of redundancy in your current code. Starting with the if-checks, here's how I would approach this:
var sourceDirectory = new DirectoryInfo(sourceFolder); // remember this, it is reused
if (sourceDirectory.Exists)
{
// Look for the files in the directory, if none found, will be empty array
foreach (var file in sourceDirectory.GetFiles(pattern))
{
file.MoveTo(Path.Combine(destinationFolder, file.Name));
}
// Re-check the directory for any remaining files
if (sourceDirectory.GetFiles(pattern).Length == 0) //Before deleting make sure that Temp folder is empty.
sourceDirectory.Delete(); // Delete Temp folder after moving all the contents.
}
As a small performance improvement, you could replace sourceDirectory.GetFiles() with sourceDirectory.EnumerateFiles() in the for-loop. This will allow you to start moving them as the method finds them, not after they have all been found.
You are passing "*.txt" into the File.Exists() call when you need to be passing a path.
You can read the Documentation here
Alternatively you could use something like this:
Directory.GetFiles(destinationFolder).Contains(filename)
I agree with David here but also I think the flow of you logic should be adjusted a bit. The File.Exixts(filename); should occur inside the foreach.
That will allow you to iterate each file and if it exists do something.
Try adding the following to check if any files exist in the location:
bool exist = Directory.EnumerateFiles(sourceFolder, "*.txt").Any();
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.
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.