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!
Related
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()
:)
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;
}
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());
}
}
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");
I'm trying to search for files of extension .dcm, by entering either the filename or the content of the file. I am able to search in a directory, but when i try searching in a drive, I get an error that says missing directory or an assemble reference.
string startFolder = #"C:\";
// Take a snapshot of the file system.
System.IO.DriveInfo dir = new System.IO.DriveInfo(startFolder);
// This method assumes that the application has discovery permissions
// for all folders under the specified path.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.
SearchOption.
AllDirectories);
Try to search in drive like in folder it works:
string startFolder = #"c:\";
DirectoryInfo directoryInfo = new DirectoryInfo(startFolder);
IEnumerable<System.IO.FileInfo> fileList = directoryInfo.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
Use this recursive function to avoid exceptions:
public static IEnumerable<string> GetFiles(string path, string pattern)
{
IEnumerable<string> result;
try
{
result = Directory.GetFiles(path, pattern);
}
catch (UnauthorizedAccessException)
{
result = new string[0];
}
IEnumerable<string> subDirectories;
try
{
subDirectories = Directory.EnumerateDirectories(path);
}
catch (UnauthorizedAccessException)
{
subDirectories = new string[0];
}
foreach (string subDirectory in subDirectories)
{
IEnumerable<string> subFiles = GetFiles(subDirectory, pattern);
result = result.Concat(subFiles); //This is LINQ concatenation
}
return result;
}
static void Main(string[] args)
{
string startFolder = #"c:\";
foreach (string fileName in GetFiles(startFolder, "*.chm"))
{
Console.WriteLine(fileName);
}
You can filter out immediatelly all the files with *.dcm extension
string startFolder = #"c:\";
DirectoryInfo directoryInfo = new DirectoryInfo(startFolder);
IEnumerable<System.IO.FileInfo> fileList = directoryInfo.GetFiles("*.dcm", System.IO.SearchOption.AllDirectories);
After that use foreach loop to find either a file with the desired name or open the file for reading and search for the value inside the file.
Are *.dcm text-based files or binary files? If they are text-based files you could use regulare expression to figure out whether the search string exists or not.
EDIT: Here is the sample recursive function that does the job. It is a console application so adapt it for your needs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace FileSearcher
{
class Program
{
static string searchValue = "Windows";
static List<FileInfo> files = new List<FileInfo>();
static void Main(string[] args)
{
string startFolder = #"C:\";
DirectoryInfo diParent = new DirectoryInfo(startFolder);
FindSearchValue(diParent);
foreach (var file in files)
{
Console.WriteLine("{0}", file.FullName);
}
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
/// <summary>
/// Recursive function that searches for a file that matches the criteria.
/// If the file is not found, the current file is opened and it's contents is
/// scanned for search value.
/// </summary>
/// <param name="diParent">Current parent folder being searched.</param>
private static void FindSearchValue(DirectoryInfo diParent)
{
FileInfo[] foundFiles = diParent.GetFiles("*.doc");
foreach (var file in foundFiles)
{
Console.WriteLine(file.FullName);
if (file.FullName.Contains(searchValue)) // There is a search string in a file name
{
files.Add(file);
}
else
{
string fileContents = File.ReadAllText(file.FullName);
if (fileContents.Contains(searchValue)) // Here you can use Regex.IsMatch(fileContents, searchValue)
{
files.Add(file);
}
}
}
foreach (var diChild in diParent.GetDirectories())
{
try
{
FindSearchValue(diChild);
}
catch (Exception exc)
{
Console.WriteLine("ERROR: {0}", exc.Message);
}
}
}
}
}
This function uses try-catch block to intercept exceptions that might occur. For example, file not found or access denied. Hope this helps!