This question already has answers here:
Get a list of all resources from an assembly
(2 answers)
Closed 7 days ago.
I have some files in a "FileFolder" folder in a project. Path to this folder:
pack://application:,,,/MyProject;Component/FileFolder/
All files in the "Build action" property are set to "Resource".
How to get a list of filenames from code?
This code might work.
DirectoryInfo directoryInfo = new DirectoryInfo("YOUR PATH");
FileInfo[] files = directoryInfo.GetFiles();
foreach (FileInfo fileInfo in files)
{
richTextBox1.Text += fileInfo.Name + "\n";
}
Related
This question already has answers here:
Getting the folder name from a full filename path
(12 answers)
Closed 5 months ago.
I have code which looks for .ini files in all folders in root directory. I want to show only folder those .ini files are in, that is only info relevant to me, because it shows different project names. But as far I can figure it out I can only show full path to file or only file itself in listbox. Any help?
My code:
private void Form1_Load(object sender, EventArgs e)
{
string rootdir = #"C:\Users\isaced1\Desktop\test"; //root directory of all projects
string[] files = Directory.GetFiles(rootdir, "Project_config.ini", SearchOption.AllDirectories); //searches for specific .ini files in all directories whithin rood directory
//cycles through all .ini files and adds it to lsitbox1 or listbox2
foreach (string item in files)
{
string fileContents = File.ReadAllText(item); //reads all .ini files
const string PATTERN = #"OTPM = true"; //search pattern in .ini files
Match match = Regex.Match(fileContents, PATTERN, RegexOptions.IgnoreCase); //matches pattern with content in .ini file
if (match.Success)
{
listBox1.Items.Add(Path.GetDirectoryName(item)); //if match is successfull places file in lisbox1
listBox1.ForeColor = Color.Green;
}
else
{
listBox2.Items.Add(Path.GetDirectoryName(item)); //if match is unsuccessfull places file in lisbox2
listBox2.ForeColor = Color.Red;
}
}
}
listBox1.Items.Add(new Uri(Path.GetDirectoryName(item)).Segments.Last())
This one worked perfectly!
This question already has answers here:
Ignore folders/files when Directory.GetFiles() is denied access
(8 answers)
Closed 5 years ago.
I'm creating a method to handle file exceptions.
I have listed all files in a directory and search for subdirectories and list all files in those subdirectories too on the C:\Users\ folder
listBox1.Items.AddRange(Directory.GetFiles("C:\\Users\\", "*", SearchOption.AllDirectories));
Some files are protected by windows, and when you run a command for those files it gives me an exception.
If there is any possible, How can I save the files that returned the exception to another listbox when the exception happens and continue listing the files to first listbox?
try this:
private List<string> GetFiles(string path, string pattern)
{
var files = new List<string>();
try
{
files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));
foreach (var directory in Directory.GetDirectories(path))
files.AddRange(GetFiles(directory, pattern));
}
catch (UnauthorizedAccessException ex)
{
// unnautorized files, create another list and add here.
}
return files;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I've a folder("App_data_payroll") which is in D Drive . I need to Find this folder and I need to copy the Files of that Folder, if the folder has files, and I have to paste that files in another folder using C#...
Find the folder path using GetDirectories, then loop over each file within the folder. Use System.IO.File.Copy to copy the files to a target location.
string dir = Directory.GetDirectories(#"D:\","App_data_payroll").FirstOrDefault();
string targetPath = "D:\CopyToFolder\";
if (System.IO.Directory.Exists(dir))
{
string[] files = System.IO.Directory.GetFiles(dir);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
var fileName = System.IO.Path.GetFileName(s);
var destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
Try using Directory.GetDirectories() to get a list of directories matching your specific pattern.
Directory.GetDirectories(path, searchPattern);
What you can do is that first check if folder exist on a specified path like this:
if(Directory.Exists("path"))
If the directory exists you can Copy its content to another folder using :
//copies all files in the folder
foreach(var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
//copies all folders in the folder
foreach(var directory in Directory.GetDirectories(sourceDir))
Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
Ref: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
The following function will help you to do this operation, this will accept two parameters
Directory name to search
Base directory ( in which search operation is performed), is optional
will collect the files within the directory and moved to specific location if exist
private static void PerformFileCopy(string DirectoryToSearch, string BaseDirectory = #"D:\")
{
if (Directory.Exists(BaseDirectory))// check for existance of base directory to avoid throwing exception
{
var searchDir = Directory.GetDirectories(BaseDirectory).Where(x => new DirectoryInfo(x).Name == DirectoryToSearch).ToList();
string copyToLocation = #"E:\newDir";
if (searchDir.Count > 0) // True if such directory found
{
foreach (var file in Directory.GetFiles(searchDir[0])) // will iterate if Directory has files
{
File.Copy(file, copyToLocation, true);
}
}
}
}
How to call this method:
option 1 : PerformFileCopy("App_data_payroll");
option 2 : PerformFileCopy("App_data_payroll",#"D:\BaseFolder\MyDir");
This question already has answers here:
Find a file with a certain extension in folder
(6 answers)
Closed 7 years ago.
How to check if any .txt file exists in a folder?
If the folder still have .txt file output a error messagebox.
Thx all! Actually i want to make a function can check any .txt file exists in a folder. If yes write a error message to eventLog.
Final My code:
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
DirectoryInfo di = new DirectoryInfo(#"c:/Users/Public/Definitions");
FileInfo[] TXTFiles = di.GetFiles("*.txt");
foreach (var fi in TXTFiles)
{
if (fi.Exists)
{
appLog.Source = "Definitions Folder still have text files";
appLog.WriteEntry("Still have txt files.");
}
}
You can check like below :
DirectoryInfo dir = new DirectoryInfo(#"c:\Directory");
FileInfo[] TXTFiles = dir.GetFiles("*.txt");
if (TXTFiles.Length == 0)
{
//No files present
}
foreach (var file in TXTFiles)
{
if(file.Exists)
{
//.txt File exists
}
}
You can use the Directory.EnumerateFiles like this:
if(Directory.EnumerateFiles(folder, "*.txt",SearchOption.TopDirectoryOnly).Any())
Foo();
See more here Directory.EnumerateFiles Method
You can do it like this
string[] files = System.IO.Directory.GetFiles(path, "*.txt");
if(files.Length >= 1)
{
MessageBox.Show("Error Message ... Your folder still have some Txt files left");
// or
Console.WriteLine("Error Message ... Your folder still have some Txt files left");
}
How can I list the text files in a certain directory (C:\Users\Ece\Documents\Testings) in a listbox of a WinForm(Windows application)?
// What directory are the files in?...
DirectoryInfo dinfo = new DirectoryInfo(#"C:\TestDirectory");
// What type of file do we want?...
FileInfo[] Files = dinfo.GetFiles("*.txt");
// Iterate through each file, displaying only the name inside the listbox...
foreach( FileInfo file in Files )
{
listbox1.Items.Add(file.Name);
}
// A statement, followed by a smiley face...
That oughta do it. ;o)
To get the txt files, try this:
var folder = #"C:\Users\Ece\Documents\Testings";
var txtFiles = Directory.GetFiles(folder, "*.txt");
listBox.Items.AddRange(txtFiles);