Is there a simple way to display the files in a folder to a CSV that shows whether the files in that folder are JPG, PDF, or other using C#?
CodePudding user response:
There is no built-in way to do this in C#, but you can use the System.IO.Directory
and System.IO.File
classes to get a list of files in a directory and then check their extensions to see if they are JPG, PDF, or other.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string directory = "C:\\";
string[] files = Directory.GetFiles(directory);
using (StreamWriter writer = new StreamWriter("files.csv"))
{
foreach (string file in files)
{
string extension = Path.GetExtension(file);
writer.WriteLine("{0},{1}", file, extension);
}
}
}
}
CodePudding user response:
You can use Matcher to traverse a folder structure using wild cards to getting specific file types and exclusions also.
Example method
public static async Task Demo(string parentFolder, string[] patterns, string[] excludePatterns, string fileName)
{
StringBuilder builder = new StringBuilder();
Matcher matcher = new();
matcher.AddIncludePatterns(patterns);
matcher.AddExcludePatterns(excludePatterns);
await Task.Run(() =>
{
foreach (string file in matcher.GetResultsInFullPath(parentFolder))
{
builder.AppendLine(file);
}
});
await File.WriteAllTextAsync("TODO", builder.ToString());
}
Example call, find all png
and pdf
files but exclude some specified in the exclude array which is explained in the docs.
string[] include = { "**/*.png", "**/*.pdf" };
string[] exclude = { "**/*in*.png", "**/*or*.png" };
await GlobbingOperations.Demo(
"Parent folder",
include,
exclude,
"Dump.txt");
When traversing files add any other logic to get specifics about a file and use that to add to the builder
variable for writing to a file.