Issue trying to count number of file in directories + subdirectories - c#

As the title says I'm trying to count the number of file in a directory and subdirectories.
I tried with a foreach loop like that :
public static int hello(string path)
{
string[] files = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
int cpt = 0;
foreach (var file in files)
{
try
{
Console.WriteLine(file);
cpt++;
}
catch { }
}
foreach (var directory in dirs)
{
try
{
hello(directory);
}
catch { }
}
return cpt;
}
And the returned value is always the number of file contained in the first path, the cpt var don't get incremented by the number of files in the others directories and subdirectories.
It's strange since the Console.WriteLine(file) shows all the files path in the console box.
It looks like a small issue but I don't really know how to solve it, I don't want to use SearchOption method but I really want to use cpt and increment it at each file.

SOLVED with the following code :
public static int hello(string path)
{
string[] files = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
int cpt = 0;
foreach (var file in files)
{
try
{
Console.WriteLine(file);
cpt++;
}
catch { }
}
foreach (var directory in dirs)
{
try
{
cpt+=hello(directory);
}
catch { }
}
return cpt;
}
Thanks to #steryd !

When you descend down the directories you're not saving the count. cpt is unique for each invocation of hello()

Related

Count the number of files with specific extension

:)
So I have a hw (I have to run project from console): I have to count the number of sub directories in specific directory (the user writes in this way " [path] [extension] [-r] ")
So if user writes the directory and doesn't write the extension, my program just counts the number of sub directories.
BUT if user writes the parameter, for example, .exe, .txt, .cs, I have to count the number of files with this specific extension in the specific directory and return this number.
Sooo, everything is good with the first part - my program works correctly and count the number of sub directories, recursively (if I write the parameter -r) or not (if I don't). The problem is with counting files with extension.
Here is my function for counting sub directories:
class Data
{
public string curDir = Directory.GetCurrentDirectory();
public string Extension = "";
public bool isRecursive;
}
public static int CountDir(Data data)
{
string[] dirs = Directory.GetDirectories(data.curDir);
int res = dirs.Length;
int resFiles = files.Length;
try
{
if (data.isRecursive)
{
foreach (string subdir in dirs)
{
Data d = new Data();
d.curDir = subdir;
d.Extension = data.Extension;
d.isRecursive = data.isRecursive;
res += CountDir(d);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
return res;
}
So I tried to do the similar thing in this method, but for files and I'm a bit confused:
string[] files = Directory.GetFiles(data.curDir);
int resFiles = files.Length;
foreach (string ext in files)
{
FileInfo fi = new FileInfo(ext);
if (data.Extension != "")
{
if (fi.Extension == data.Extension)
{
//res = 0;
//++res;
//what am I supposed to do here?..
}
}
}
I also wonder if I can do this in the same method (CountDir).
Thank you so much in advance!
Edit: I know about SearchOptions.AllDirectories method, but I don't know in advance which extension user will write
I would put the file count logic in its own method since the goal is to get the number of files for a specific directory rather than all sub-directories. Here's an example based on your sample code:
public static int countFiles(Data data)
{
string[] files = new string[0];
try
{
files = Directory.GetFiles(data.curDir, $"*{data.Extension}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
return files.Length;
}

C# - Count all Files in directory including Zip in Zip etc

I have a directory where all kind of random data is in it including ZIP archives which could also include ZIP archives itself and so on. What I want to count is all data except the ZIP archives.
My attempt with starting to count the data in the ZIP files:
static void Main(string[] args)
{
DirectoryInfo directoryInfo = new DirectoryInfo(#"C:\Temp");
int count = 0;
foreach (FileInfo file in directoryInfo.GetFiles())
{
if (file.Extension.Equals(".zip"))
{
count += ZipFileCount(file.FullName);
}
}
Console.WriteLine(count);
}
public static int ZipFileCount(String zipFileName)
{
using (ZipArchive archive = ZipFile.Open(zipFileName, ZipArchiveMode.Read))
{
foreach (var entry in archive.Entries)
{
if (!String.IsNullOrEmpty(entry.Name))
{
count += 1;
if (entry.Name.Substring(entry.Name.Length - 3).Equals("zip"))
{
ZipFileCount(entry.Name);
}
}
}
return count;
}
}
That didn't work out as ZipFileCount(entry.Name) does not provide the right entries in the ZIP of the ZIP.
Anybody can help me out to fix this?
One way of accomplishing it is extracting all the zips to a temporary folder recursively and then count for non-zip files inside of those directories. Once we get the count we can delete the intermediate files and revert the system to initial state. Remember the user needs to have write permissions on the file system to run the code in that particular directory.
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo directoryInfo = new DirectoryInfo(#"C:\Temp");
ProcessDirectory(directoryInfo); // Process the directory and extract any zip files.
int count = 0;
foreach (DirectoryInfo subdirectory in directoryInfo.EnumerateDirectories())
{
if (subdirectory.Name.EndsWith(".ExtractedFiles")) // Count only extracted zip files in root directory.
{
count = CountFiles(subdirectory, count);
}
}
DeleteIntermediateFiles(directoryInfo); // Delete the extracted files.
Console.WriteLine(count);
}
public static void ProcessDirectory(DirectoryInfo directoryInfo)
{
foreach (DirectoryInfo subdirectory in directoryInfo.EnumerateDirectories())
{
ProcessDirectory(subdirectory); //Process subdirectories.
}
ProcessFiles(directoryInfo); //Process files.
}
private static void ProcessFiles(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.EnumerateFiles())
{
if (file.Extension.Equals(".zip")) // extract zip files.
{
var extractFilesDirectory = directoryInfo.CreateSubdirectory(
Path.GetFileNameWithoutExtension(file.Name) + ".ExtractedFiles");
ZipFile.ExtractToDirectory(file.FullName, extractFilesDirectory.FullName);
ProcessDirectory(extractFilesDirectory); //process extracted files.
}
}
}
public static int CountFiles(DirectoryInfo directoryInfo, int count)
{
foreach (DirectoryInfo subdirectory in directoryInfo.EnumerateDirectories())
{
count = CountFiles(subdirectory, count);
}
foreach (var fileInfo in directoryInfo.GetFiles())
{
if (fileInfo.Extension != ".zip") //exclude zip files while counting.
count++;
}
return count;
}
public static void DeleteIntermediateFiles(DirectoryInfo directoryInfo)
{
foreach (DirectoryInfo subdirectory in directoryInfo.EnumerateDirectories())
{
if (subdirectory.Name.EndsWith(".ExtractedFiles"))
{
Directory.Delete(subdirectory.FullName, true);
}
}
}
}
}

Proceed If File Doesn't Exist

I have the following code:
public static void readtext(string pathtoText)
{
if (File.Exists(pathtoText))
{
string[] lines = System.IO.File.ReadAllLines(pathtoText);
// Display the file contents by using a foreach loop.
foreach (string line in lines)
{
clearPath(line);
}
}
else
{
Console.WriteLine("{0} doesn't exist, or isn't a valid text file", pathtoText);
}
}
public static void clearPath(string path)
{
if(Directory.Exists(path))
{
int directoryCount = Directory.GetDirectories(path).Length;
if(directoryCount > 0)
{
Console.WriteLine("{0} has Subdirectories to Remove", path);
DirectoryInfo di = new DirectoryInfo(path);
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
else
{
Console.WriteLine("{0} has no directories to remove", path);
}
int fileCount = Directory.GetFiles(path).Length;
if (fileCount > 0)
{
Console.WriteLine("{0} has files to Remove", path);
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch(System.IO.IOException)
{
Console.WriteLine("Please Close the following File {0}", file.Name);
}
}
}
}
else
{
Console.WriteLine("Path Doesn't Exist {0}", path);
}
}
My function reads directories from a text file and passes it to clearPath which checks if the directory exists, and if so, cleans it. My problem is that, if a directory doesn't exist, it stops the program(it doesn't move to the next directory to check if it exists and clean, the for each loop just stops) .
How do I get it to the next directory even if specific directory doesn't exist?
it is possible that you have empty lines in your file?
you can try something like that:
foreach (string line in lines)
{
if (!String.IsNullOrWhiteSpace(line))
{
clearPath(line.trim());
}
}

Deleting a specific folder and it's files ASP.NET

Alright so I'm having a bit of an issue here. I'm trying to delete a specific folder inside another folder on my webserver using ASP.NET (C#) The folder being deleted is based on a textbox.
The directory is like this
/images/folderx
folderx = txtDelFolder.Text;
The problem is that everything I try deletes every single thing inside the images folder. I'm guessing that it is not recognizing my folder in the filepath
string path = #"\httpdocs\images\ +
txtDelFolder.Text;
I have also tried
string path = #"\httpdocs\images\ +
txtDelFolder.Text + "\";
Tried all this with both single '\' and double '\'
Would appreciate any help on this
Also where it says <directfilepath> I actually have the filepath typed out, just didn't want to share that here.
****edit****
string path = Server.MapPath("~/imagestest/" + txtEditTitle.Text);
if(Directory.Exists(path))
{
DeleteDirectory(path);
}
}
}
private void DeleteDirectory(string path)
{
foreach(string filename in Directory.GetFiles(path))
{
File.Delete(filename);
}
foreach(string subfolders in Directory.GetDirectories(path))
{
Directory.Delete(subfolders, true);
}
}
Try this:
private void DeleteFiles(string folder)
{
string path=Server.MapPath("~/httpdocs/images/" + folder);
string[] files=Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
File.Delete(file);
}
//then delete folder
Directory.Delete(path);
}
try this one :
public void DeleteFolder(string folderPath)
{
if (!Directory.Exists(folderPath))
return;
// get the directory with the specific name
DirectoryInfo dir = new DirectoryInfo(folderPath);
try
{
foreach (FileInfo fi in dir.GetFiles())
fi.Delete();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Don't see why this wouldn't work:
public static bool DeleteDirectory(string input)
{
if (Directory.Exists(input))
{
Directory.Delete(input, true);
return !Directory.Exists(input);
}
else
return true;
}
string thePath = Server.MapPath(#"~/images/");
thePath = Path.Combine(Path.GetFullPath(thePath), txtInput.Text);
if(DeleteDirectory(thePath))
Console.WriteLine("YAY");
else
Console.WriteLine("BOO");

Split directories using recursion and string.split

Here's my problem. I'm using C# and I'm supposed to design a program that runs a directory and list all of the sub-directories and files within. I've got the basic code down, which is shown below:
namespace DirectorySearch
{
class DirectorySearch
{
const string PATH = #"C:\Directory Search";
static void Main(string[] args)
{
DirSearch(PATH);
}
static void DirSearch(string dir)
{
try
{
foreach (string f in Directory.GetFiles(dir))
Console.WriteLine(f);
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(d);
DirSearch(d);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
The problem I'm having is I'm supposed to use stringName.Split('/').Last so the output is all in one straight line, but I have no idea where to place it in the code. The output is supposed to look like:
C:\Directory Search
File1.txt
File2.txt
Folder1
Folder2
File3.txt
Folder3
and so on... I'm pretty sure I can figure out how to make the tabs work after I figure out how to split them up. Any help would be greatly appreciated.
Try this
Console.WriteLine(f.Split('\\').Last());
You just need to use Path.GetFilename which returns directory name (for directories) or file name with extension
foreach (string f in Directory.GetFiles(dir))
Console.WriteLine(Path.GetFileName(f));
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(Path.GetFileName(d));
DirSearch(d);
}
I'm Not sure if you'r looking for something like this, but you can try this code
namespace DirectorySearch
{
class DirectorySearch
{
const string PATH = #"C:\Directory Search";
static void Main(string[] args)
{
Console.WriteLine(PATH);
DirSearch(PATH);
}
static void DirSearch(string dir, int depth = 1)
{
try
{
string indent = new string('\t', depth);
foreach (string f in Directory.GetFiles(dir))
Console.WriteLine(indent + f.Split('\\').Last());//using split
//Console.WriteLine(indent + Path.GetFileName(f));//using Get File name
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(indent + d.Split('\\').Last()); //using split
//Console.WriteLine(indent + Path.GetFileName(d)); //using Get File name
DirSearch(d, depth++);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Hope this helps you!

Categories