how to display files inside directory - c#

i am trying to get list of files inside the directory in this case "c:\dir\" (ofcourse i have files inside) and i wanted to display the name of those files in console program build in c#....
initially i did this....
static class Program
{
static void Main()
{
string[] filePaths = Directory.GetFiles(#"c:\dir\");
Console.WriteLine();
Console.Read();
}
}
how can i see the name of those files.......
any help would be appreciated.....
thank you.
(further i would like to know if possible any idea on sending those file path towards dynamic html page.... any general concept how to do that...)

If by "file names" you mean literally just the names and not the full paths:
string[] filePaths = Directory.GetFiles(#"c:\dir");
for (int i = 0; i < filePaths.Length; ++i) {
string path = filePaths[i];
Console.WriteLine(System.IO.Path.GetFileName(path));
}

Loop through the files and print them one at a time:
foreach(string folder in Directory.GetDirectories(#"C:\dir"))
{
Console.WriteLine(folder);
}
foreach(string file in Directory.GetFiles(#"C:\dir"))
{
Console.WriteLine(file);
}

foreach (string filename in filePaths) {
Console.WriteLine(filename);
}

Keep in mind that if there are many files in the folder you will have memory problems. .Net 4.0 contains a fix: C# directory.getfiles memory help

foreach(FileInfo f in Directory.GetFiles())
Console.Writeline(f.Name)

Related

Output an index number and remove the path from file

I wrote this code, it works but there are 2 features I'd like to implement and I can't find out how.
First:
How to add an index number before each song so it looks like this:
Song1
Song2
Song3
Second:
The output to file includes the path to the file. How do I remove it?
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string[] files = Directory.GetFiles("E:\\Music", "*", SearchOption.AllDirectories);
foreach (string file in files)
{
string FileName = Path.GetFileName(file);
Console.WriteLine(FileName);
System.IO.File.WriteAllLines("E:\\songs.txt", (files));
}
Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
}
}
So, in order to only write the name of the songs and not the whole path, you'll have to use Path.GetFileNameWithoutExtensions.
To write the index before every song, you'll have to switch to a for loop (to work with the index).
Another problem is that you're writing to songs.txt for every song, which is bad. Here's a code to help you out:
string[] files = Directory.GetFiles(#"C:\Users\Admin\Music\Playlists", "*", SearchOption.AllDirectories);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < files.Length; i++)
{
sb.AppendLine($"{i + 1}. {Path.GetFileNameWithoutExtension(files[i])}");
// Each line will be something like: Number. NameOfTheSong
}
// Only save to the file when everything is done
File.WriteAllText("E:\\songs.txt", sb.ToString());
Console.WriteLine("Press any key to exit");
Console.ReadLine();
First of all, I think that you have a problem with this line:
System.IO.File.WriteAllLines("E:\\songs.txt", (files));
Because in every loop you are writting the file songs.txt
About the new features:
For getting the index, an easy way is to change the foreach loop by a for loop.
For getting the file name you can use Path.GetFileName() or Path.GetFileNameWithoutExtension()
I hope this can help you.

Get directories and files with recursion?

Is possible to get all directories, subdirectories and files with recursion.
I do this because i want to increase my programming logic, and learn how recursion work.
I know to do that with this way:
string path = "D://";
string rezdir,newpath;
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] dir = di.GetDirectories().ToArray();
for (int i = 0; i < di.GetDirectories().Length; i++)
{
Console.WriteLine(dir[i].ToString());
}
Console.WriteLine("\n\nChoose File: ");
rezdir = Console.ReadLine();
newpath = path + rezdir;
di = new DirectoryInfo(newpath);
dir = di.GetDirectories().ToArray();
for (int i = 0; i < di.GetDirectories().Length; i++)
{
Console.WriteLine(dir[i].ToString());
}
Console.ReadKey();
But i don't do that with recursion way, so ff someone can to do this, i'll be grateful to him.
Going by the code you posted - you seem to want some user interaction - so try something like this:
public static class RecursiveTest
{
public static string Foo(DirectoryInfo currentPath)
{
if (!currentPath.Exists) return string.Empty;
foreach (var directory in currentPath.EnumerateDirectories())
Console.WriteLine("Directory {0}", directory.Name);
foreach (var file in currentPath.EnumerateFiles())
Console.WriteLine("File {0}", file.Name);
while(true)
{
Console.WriteLine("Choose directory or file: ");
string chosenPath = Console.ReadLine();
string newPath = Path.Combine(currentPath.FullName, chosenPath);
if(Directory.Exists(newPath))
return Foo(new DirectoryInfo(newPath));
if(File.Exists(newPath))
return newPath;
Console.WriteLine("File {0} doesn't exist!", newPath);
}
}
}
And call with something like this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(RecursiveTest.Foo(new DirectoryInfo(#"d:\dev")));
Console.ReadLine();
}
}
HTH
I will avoid coding, because this is a valuable learning exercise. Try completing it yourself: once you do, you'll know that you understand recursion.
To be recursive, a method needs to call itself. Imagine that a method
public static void ShowDirectory(int indentationLevel, DirectoryInfo path)
is already written for you. This makes it easier to write the body:
Get all files in the directory, and print their names in the loop
Get all directories in the directory, and show their content at the next indentation level. You need another loop for that.
The first step is a simple exercise in writing loops. The second exercise becomes easy, too, because you can think of the ShowDirectory as pre-written.
Yeah, it's possible. But I do recommend that you first take a grasp of what recursion is. To put it simply, a recursion has a one-time executing part, and many-time executing part. That one time triggers the many-time part.
In this question, the one-time execution part might be to get the list of all directories beneath the root directory.
Then for each directory, you get all the sub-directories and files. This is the many-times part. However, to run a batch of codes many times, you need to bundle them into a callable routine, or procedure, or method, or function, whatever you call it. Just code bundle.
public void DoDirectories()
{
// one-time part; get a list of directories to start with.
List<string> rootDirectories = Directory.GetDirectories("c:\\").ToList();
foreach (string rootDirectory in rootDirectories)
{
GetSubdirectories(rootDirectory);
}
}
public List<string> GetSubdirectories(string parentDirectory)
{
List<string> subdirecotries = Directory.GetDirectories(
parentDirectory, "*.*", SearchOption.TopDirectoryOnly).ToList();
foreach (string subdirectory in subdirecotries)
{
GetSubdirectories(subdirectory); // recursing happens here
}
return subdirecotries;
}

How to get list of directories containing particular file using c#

I wish to get list of all the folders/directories that has a particular file in it. How do I do this using C# code.
Eg: Consider I have 20 folders of which 7 of them have a file named "abc.txt". I wish to know all folders that has the file "abc.txt".
I know that we can do this by looking thru all the folders in the path and for each check if the File.Exists(filename); But I wish to know if there is any other way of doing the same rather than looping through all the folder (which may me little time consuming in the case when there are many folders).
Thanks
-Nayan
I would use the method EnumerateFiles of the Directory class with a search pattern and the SearchOption to include AllDirectories. This will return all files (full filename including directory) that match the pattern.
Using the Path class you get the directory of the file.
string rootDirectory = //your root directory;
var foundFiles = Directory.EnumerateFiles(rootDirectory , "abc.txt", SearchOption.AllDirectories);
foreach (var file in foundFiles){
Console.WriteLine(System.IO.Path.GetDirectoryName(file));
}
EnumerateFiles is only available since .NET Framework 4. If you are working with an older version of the .NET Framework then you could use GetFiles of the Directory class.
Update (see comment from PLB):
The code above will fail if the access to a directory in denied. In this case you will need to search each directory one after one to handle exceptions.
public static void SearchFilesRecursivAndPrintOut(string root, string pattern)
{
//Console.WriteLine(root);
try
{
var childDireactory = Directory.EnumerateDirectories(root);
var files = Directory.EnumerateFiles(root, pattern);
foreach (var file in files)
{
Console.WriteLine(System.IO.Path.GetDirectoryName(file));
}
foreach (var dir in childDireactory)
{
SearchRecursiv(dir, pattern);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
The following shows how to narrow down your search by specific criteria (i.e. include only DLLs that contain "Microsoft", "IBM" or "nHibernate" in its name).
var filez = Directory.EnumerateFiles(#"c:\MLBWRT", "*.dll", SearchOption.AllDirectories)
.Where(
s => s.ToLower().Contains("microsoft")
&& s.ToLower().Contains("ibm")
&& s.ToLower().Contains("nhibernate"));
string[] allFiles = filez.ToArray<string>();
for (int i = 0; i < allFiles.Length; i++) {
FileInfo fInfo = new FileInfo(allFiles[i]);
Console.WriteLine(fInfo.Name);
}

Find a file with particular substring in name

I have a dirctory like this "C:/Documents and Settings/Admin/Desktop/test/" that contain a lot of microsoft word office files. I have a textBox in my application and a button. The file's name are like this Date_Name_Number_Code.docx. User should enter one of this options, my purpose is to search user entry in whole file name and find and open the file.
thank you
string name = textBox2.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
MessageBox.Show("Match Found : " + file);
}
}
G'day,
Here's the approach I used. You'll need to add a textbox (txtSearch) and a button (cmdGo) onto your form, then wire up the appropriate events. Then you can add this code:
private void cmdGo_Click(object Sender, EventArgs E)
{
// txtSearch.Text = "*.docx";
string[] sFiles = SearchForFiles(#"C:\Documents and Settings\Admin\Desktop\test", txtSearch.Text);
foreach (string sFile in sFiles)
{
Process.Start(sFile);
}
}
private static string[] SearchForFiles(string DirectoryPath, string Pattern)
{
return Directory.GetFiles(DirectoryPath, Pattern, SearchOption.AllDirectories);
}
This code will go off and search the root directory (you can set this as required) and all directories under this for any file that matches the search pattern, which is supplied from the textbox. You can change this pattern to be anything you like:
*.docx will find all files with the extention .docx
*foogle* will find all files that contain foogle
I hope this helps.
Cheers!
You can use Directory.GetFiles($path$).Where(file=>file.Name.Contains($user search string$).
Should work for you.
You can use the Directory.GetFiles(string, string) which searches for a pattern in a directory.
So, for your case, this would be something like:
string[] files =
Directory.GetFiles("C:/Documents and Settings/Admin/Desktop/test/",
"Date_Name_Number_Code.docx");
Then look through the files array for what you are looking for.
if you need info about the files instead of content:
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

Move multiple sub folders to a different directory and keep the folder names

Please could a C# expert help with a simple problem which for some strange reason I just can't seem to work out? I'm trying to move multiple sub folders in the current directory to a new directory and keep the subfolder name, see below:
public string currentDirectory = System.Environment.GetEnvironmentVariable("LOCALAPPDATA") + #"\Test\CurrentFolder\";
public string newDirectory = System.Environment.GetEnvironmentVariable("LOCALAPPDATA") + #"\Test\NewFolder\";
private void btnMoveFolder_Click(object sender, RoutedEventArgs e)
{
string[] subdirectoryEntries = Directory.GetDirectories(currentDirectory);
try
{
foreach (string subCurrentDirectory in subdirectoryEntries)
{
Directory.Move(subCurrentDirectory, newDirectory);
}
}
catch (System.Exception)
{
Log("Problem with moving the directory.");
}
}
At the moment, I only seem to be able to move one folder instead of all of the them.
Any help would be greatly appreciated!
I suppose you want this:
Directory.Move(subCurrentDirectory,
Path.Combine(
newDirectory,
Path.GetFileName(subCurrentDirectory)));
Try this out:
DirectoryInfo subfolder = new DirectoryInfo(#"OLDPATH\DirectoryToMove");
subfolder.MoveTo(#"NEWPATH\DirectoryToMove");
Just make sure you include the name of the directory to move in both the old AND new filepaths.
In general DirectoryInfo and FileInfo are much more useful than Directory and File in most situations.

Categories