Find all files in a folder - c#

I am looking to create a program that finds all files of a certain type on my desktop and places them into specific folders, for example, I would have all files with .txt into the Text folder.
Any ideas what the best way would be to accomplish this? Thanks.
I have tried this:
string startPath = #"%userprofile%/Desktop";
string[] oDirectories = Directory.GetDirectories(startPath, "");
Console.WriteLine(oDirectories.Length.ToString());
foreach (string oCurrent in oDirectories)
Console.WriteLine(oCurrent);
Console.ReadLine();
It was not successful in finding all of the files.

A lot of these answers won't actually work, having tried them myself. Give this a go:
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);
foreach (var file in d.GetFiles("*.txt"))
{
Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}
It will move all .txt files on the desktop to the folder TextFiles.

First off; best practice would be to get the users Desktop folder with
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Then you can find all the files with something like
string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.
Then you could copy or move the files by enumerating the above collection like
// For copying...
foreach (string s in files)
{
File.Copy(s, "C:\newFolder\newFilename.txt");
}
// ... Or for moving
foreach (string s in files)
{
File.Move(s, "C:\newFolder\newFilename.txt");
}
Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.
With that in mind you could also check out the DirectoryInfo and FileInfo classes.
These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily
Check out these for more info:
http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
http://msdn.microsoft.com/en-us/library/ms143316.aspx
http://msdn.microsoft.com/en-us/library/system.io.file.aspx

You can try with Directory.GetFiles and fix your pattern
string[] files = Directory.GetFiles(#"c:\", "*.txt");
foreach (string file in files)
{
File.Copy(file, "....");
}
Or Move
foreach (string file in files)
{
File.Move(file, "....");
}
http://msdn.microsoft.com/en-us/library/wz42302f

Related

Why dose File.Exists not work for exe's and shortcuts [duplicate]

I am using .NET 2.0 and Linq is out of question. I would like to check if file exists inside a directory without knowledge of the file extension.
I just need this logic done.
1.Check File exists in Directory using String Filename provided using search pattern leaving out the extension of the File
2.Get the Files if they exists and Databind to provide Download links.If file does not exist then start uploading the File.
Update:
Directory.GetFiles() and DirectoryInfo.GetFiles() indeed solves the part where in i check for File existence. As for the performance regarding FileInfo objects, these were only solution to my requirements of databinding to provide download links
DirectoryInfo root = new DirectoryInfo("your_directory_path");
FileInfo[] listfiles = root.GetFiles("dummy.*");
if (listfiles.Length > 0)
{
//File exists
foreach (FileInfo file in listfiles)
{
//Get Filename and link download here
}
}
else
{
//File does not exist
//Upload
}
Hope this works
To see if a file exists with that name, can you not just use..
However, Directory.GetFiles already includes the full path
string [] files = Directory.GetFiles(Path,"name*");
bool exists = files.Length > 0;
if ( exists)
{
//Get file info - assuming only one file here..
FileInfo fi = new FileInfo(files[0]);
//Or loop through all files
foreach (string s in files)
{
FileInfo fi = new FileInfo(s);
//Do something with fileinfo
}
}
You can use DirectoryInfo.GetFiles() to have a FileInfo[] instead of a String[].

Visual C#: Move multiple files with the same extensions into another directory

guys. I've got a problem I can't solve:
I have a 2 folders I choose with folderBrowserDialog and tons of files in source directory I need to move to the target directory. But, I have only to move files with a specific extension like .txt or any other extension I can get from textbox.
So how can I do it?
First get all the files with specified extension using Directory.GetFiles() and then iterate through each files in the list and move them to target directory.
//Assume user types .txt into textbox
string fileExtension = "*" + textbox1.Text;
string[] txtFiles = Directory.GetFiles("Source Path", fileExtension);
foreach (var item in txtFiles)
{
File.Move(item, Path.Combine("Destination Directory", Path.GetFileName(item)));
}
Try this:
For copying files...
foreach (string s in files)
{
File.Copy(s, "C:\newFolder\newFilename.txt");
}
for moving files
foreach (string s in files)
{
File.Move(s, "C:\newFolder\newFilename.txt");
}
Example for Moving files to Directory:
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);
foreach (var file in d.GetFiles("*.txt"))
{
Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}
will Move all the files from Desktop to Directory "TextFiles".

How to read multiple files from server into c#

I want to know how to read multiple (about 500-1000) text files which are located on a server.
So far, I've written code for a program that only reads a single text file.
Here's how I'm currently reading a single file.
public void button1_Click(object sender, EventArgs e)
{
// Reading/Inputing column values
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] fileLines = File.ReadAllLines(ofd.FileName);
I would like to get rid of the open file dialog box, and let the program automatically read the 500-1000 text files where are located in the sever.
I'm thinking something along the lines of
for (int i =0; i<numFiles; i++)
{
//just use string[] fileLines =File.ReadAllLines()
//how would i specify the path for multiple files?
}
Questions are then:
How would I approach this?
How exactly should I get the number of files?
(I'm guessing I'd have to read the server file which contains them.)
You can use Directory.GetFiles(string path) to get all files from a certain directory. You can then use a foreach loop to iterate through all the files in that directory and do your processing.
You can use recursion to loop through all directories. Using Directory.EnumerateFiles also allows you to use a foreach loop so you don't have to worry about the file count.
private static void ReadAllFilesStartingFromDirectory(string topLevelDirectory)
{
const string searchPattern = "*.txt";
var subDirectories = Directory.EnumerateDirectories(topLevelDirectory);
var filesInDirectory = Directory.EnumerateFiles(topLevelDirectory, searchPattern);
foreach (var subDirectory in subDirectories)
{
ReadAllFilesStartingFromDirectory(subDirectory);//recursion
}
IterateFiles(filesInDirectory, topLevelDirectory);
}
private static void IterateFiles(IEnumerable<string> files, string directory)
{
foreach (var file in files)
{
Console.WriteLine("{0}", Path.Combine(directory, file));//for verification
try
{
string[] lines = File.ReadAllLines(file);
foreach (var line in lines)
{
//Console.WriteLine(line);
}
}
catch (IOException ex)
{
//Handle File may be in use...
}
}
}
Also note Directory.EnumerateFiles provides overload that lets you provide a search pattern to narrow the scope of the files.
How you go about getting your files depends on if they are all located in the same directory of if you'll need to recursively search through a directory and all child directories. Directory.GetFiles is where you want to start. It has 3 overloads seen here. So you might try something like this:
string path = "\mypath\tosomehwere";
string searchPattern = "*.txt";
string[] MyFiles = Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories);
Then just loop through the string array and proccess each file as you would normally.
foreach (string filePath in MyFiles)
{
MyFileProcessMethod(filePath)
}
Path.GetFileName(filePath) will return the individual text file name should you need it for your processing requirements.

C# Recursive Folder/File scan with Size,Path,Creation,FileVersion to txt

I am looking for a recursive function that scan a specific folder and send result in a text file.
I would like to list in a text file all files and folder with size, path, creation date, file version if existing but I have no idea on how to proceed.
I found some way to scan recursively but not to recover all needed information.
You can do the following,
GetFileInfo(string dir)
{
try
{
FileInfo info = null;
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string file in Directory.GetFiles(d))
{
info = new FileInfo(file);
//get all information using info here
}
GetFileInfo(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
Use the System.IO.FileInfo object and System.IO.DirectoryInfo object....other than that, show us what you've tried.
You can list a folder using System.IO.DirectoryInfo and System.IO.FileInfo as ganders said.If you can list one folder's content the rest is simple recursion.The idea is while listing root directory if one item in the root directory is a directory call the same function on this directory.

foreach file in folder, rename and save

I have a simple foreach here where I am have got the folder location using the folderBrowserDialog tool and am now trying to go through each one of the files and replace certain characters within the file name.
I am getting an error which says it cannot find the file when it gets to this part of the code File.Move(_FileName, _NewFileName);
Can anyone shed any light on this? Would be much appreciated.
Thanks
foreach (FileInfo Files in Folder.GetFiles())
{
_FileName = Files.Name;
_NewFileName = _FileName.Replace(" ", "-").Replace(",", "-");
File.Move(_FileName, _NewFileName);
File.Delete(_FileName);
}
You need to use Files.FullName not Files.Name
FullName includes the full path (i.e. C:\test\foo.txt) which is needed by File.Move() and File.Delete() while Name is just the file name itself (i.e. foo.txt).
Edit:
#crashmstr is correct you should not do a string replace on the full path. All in all I'd probably do it this way:
foreach (FileInfo file in Folder.GetFiles())
{
string originalFileName = file.FullName;
string fileName = file.Name.Replace(" ", "-").Replace(",", "-");
string newFileName = Path.Combine(file.DirectoryName, fileName);
File.Move(originalFileName, newFileName);
}
Also keep in mind File.Delete() is not needed here, since the original file won't be there anymore after you move it.
You are trying to remove an item from the collection which you are iterating.
You can store the list of files that you get from Folder.GetFiles() into some variable and iterate over it with foreach.

Categories