Directory.Getfiles() reads only the first file in the folder - c#

HI I need to read all the files in a directory. The code below reads only the first file even if 10 files are present in the folder. It does not throw any exception. Why is it not printing the other files name? Any help appreciated.
string[] txtFiles = Directory.GetFiles(#"D:\Sample", "*.txt");
foreach (string item in txtFiles)
{
string contents = File.ReadAllText(item);
if (contents.Contains("testing"))
{
Console.WriteLine(item);
}
}
In D:\Sample I have 10 sample files which contain the word testing in them. But it reads only Sample1.txt and does not read the rest.
Output:
Sample1.txt

Please change you File variable as file as below and try.
string[] array = Directory.GetFiles(#"D:\Sample", "*.txt");
foreach (string file in array)
{
Application.DoEvents();
string contents = File.ReadAllText(file);
if (contents.Contains("testing"))
{
Console.WriteLine(file);
}
}

Related

How can you copy a file and paste it from one location(directory) to another location (directory) in C#? [duplicate]

This question already has answers here:
copy files from one location to another
(4 answers)
Closed 8 months ago.
I want to know how to copy a file, not regarding it's type, pptx docx txt, and paste it in another address of the directory in C#. I assume that the File.Copy function is only available for .txt file, and it is not a file copy and paste, it is a contents copy and paste.
Thank you.
This code is from the Microsoft docs, apparently it can copy .jpg files and if it can it should be able to copy all file types
string sourceDir = #"c:\current";
string backupDir = #"c:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
Source: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.copy?view=net-6.0#system-io-file-copy(system-string-system-string-system-boolean)

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.

need to update image file in c#

I have 800-1000 Uniquely named folders in one large folder.
Inside of each uniquely named folder is another folder called /images.
And inside of each image folder is a file named "Rock-Star-Site-Design-{UNIQUEFOLDERNAME}-ca-logo.png"
I write a code that replaces all .png files (while keeping the original name) from a .png file which I supply.
The folder structure and filenames need to remain the same. Basically i am updating the old file with a new file, using the same (unique) name, 800-1000 times.
The code i have tried working properly but there is one mistake.There are plenty of images inside Image folder,But i need to update only "Rock-Star-Site-Design-{UNIQUEFOLDERNAME}-ca-logo.png"file every folder.
is there any way so i can get file.startwith("Rock-Star").So i can update particular file i want.
Here is my code:
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
foreach (var file in files)
{
if (!string.IsNullOrWhiteSpace(file))
{
File.Copy(Server.MapPath("ca-logo.jpg"), file,true);
}
}
}
catch (System.Exception excpt)
{
//MessageBox.Show(excpt.Message);
}
return files;
}
You can use this to get files based on a regular expression
Directory.GetFiles(sDir, "Rock-Star*.png");
Rock-Star*.png means files starting with Rock-Star, * means any character or sequence of characters, ending with .png
First get the file name from file full path using Path.GetFileName(). Then Use StartsWith(). When you add files to the list check if the file name starts with the name you want and then add to the list.
List<String> files = new List<String>();
foreach (string f in Directory.GetFiles(""))
{
//Get file name from full file path
string fileName = Path.GetFileName(f);
//Get only the files starts with Rock-Star
if (fileName.StartsWith("Rock-Star"))
{
files.Add(f);
}
}
EDIT
If you want to update the files with both upper and lower case lettes then you have to pass StringComparison.OrdinalIgnoreCase enumeration to your StartsWith() method
//Get only the files starts with Rock-Star or rock-start
if (fileName.StartsWith("Rock-Star",StringComparison.OrdinalIgnoreCase))
{
files.Add(f);
}
EDIT
To get files within all sub directories and replace, Pass SearchOption.AllDirectories to the GetFiles() method. Following code will search all the sub directories for files with .png extension
foreach (string f in Directory.GetFiles(sDir, "*.png", SearchOption.AllDirectories))

Find all files in a folder

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

Categories