C# Reading file in a directory - c#

I have an app that reads a CSV file called “words.csv”. My new requirement is that 1) it needs to ensure that there is only one CSV file in the directory before reading. 2) It should read any file with ".CSV" extension not just “words.csv” (after condition 1 is satisfied). Hope this makes sense?
Can anyone assist?
public class VM
{
public VM()
{
Words = LoadWords(fileList[0]);
}
public IEnumerable<string> Words { get; private set; }
string[] fileList = Directory.GetFiles(#"Z:\My Documents\", "*.csv");
private static IEnumerable<string> LoadWords(String fileList)
{
List<String> words = new List<String>();
if (fileList.Length == 1)
{
try
{
foreach (String line in File.ReadAllLines(fileList))
{
string[] rows = line.Split(',');
words.AddRange(rows);
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message);
}
return words;
}
}
}

You can use this code to get a list of all the csv files in a folder:
string[] fileList = Directory.GetFiles( #"Z:\My Documents\", "*.csv");
So to satisfy your conditions, this should do the trick:
string[] fileList = Directory.GetFiles( #"Z:\My Documents\", "*.csv");
if( fileList.Length == 1 )
{
//perform your logic here
}

DirectoryInfo di = new DirectoryInfo(#"Z:\My Documents");
// Get a reference to each file in that directory.
FileInfo[] fiArr = di.GetFiles();
if(fiArr.Length ==1)
{
FileInfo fri = fiArr[0];
//use fri.Extension to check for csv
//process as required
}
MSDN:DirectoryInfo.GetFiles
MSDN: FileInfo

FileInfo file = new DirectoryInfo(#"Z:\My Documents")
.EnumerateFiles("*.csv")
.SingleOrDefault();
if (file != null)
{
//do your logic
}
Linq's SingleOrDefault operator will make sure there's exactly onle file with the given pattern otherwise it will return null

Related

Issue trying to count number of file in directories + subdirectories

As the title says I'm trying to count the number of file in a directory and subdirectories.
I tried with a foreach loop like that :
public static int hello(string path)
{
string[] files = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
int cpt = 0;
foreach (var file in files)
{
try
{
Console.WriteLine(file);
cpt++;
}
catch { }
}
foreach (var directory in dirs)
{
try
{
hello(directory);
}
catch { }
}
return cpt;
}
And the returned value is always the number of file contained in the first path, the cpt var don't get incremented by the number of files in the others directories and subdirectories.
It's strange since the Console.WriteLine(file) shows all the files path in the console box.
It looks like a small issue but I don't really know how to solve it, I don't want to use SearchOption method but I really want to use cpt and increment it at each file.
SOLVED with the following code :
public static int hello(string path)
{
string[] files = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
int cpt = 0;
foreach (var file in files)
{
try
{
Console.WriteLine(file);
cpt++;
}
catch { }
}
foreach (var directory in dirs)
{
try
{
cpt+=hello(directory);
}
catch { }
}
return cpt;
}
Thanks to #steryd !
When you descend down the directories you're not saving the count. cpt is unique for each invocation of hello()

c# finding files with some extension on hard disk

I want to find all files in whole harddrive (.jpg, .png, .apk and a few other formats) but this code is not working..all it does is : for example if in my 'D:\' drive I have: 1)a image file 'i1', 2)a folder 'f1' which has image file and 3) another folder 'f2' which has image file and 'f2' contains folder 'f3' which has image file .It only performs 'calcFile()' on contents inside f1 and f2 but not on contents of f3 and i1 same happens with all other partitions .What is wrong here? Any help is appreciated.
I hope you understand what is happening because that's the easiest way I could explain my situation, if more info is required just tell me. thanks :)
public void calcDirectory(string token)
{
var validExtensions = new[]
{
".jpg", ".png", ".apk"
};
foreach (string s in Directory.GetLogicalDrives())
{
DriveInfo driveInfo = new DriveInfo(s);
if (driveInfo.IsReady)
{
foreach (string d in Directory.GetDirectories(s))
{
FileAttributes attrs1 = File.GetAttributes(d);
if (!attrs1.HasFlag(FileAttributes.ReparsePoint))
{
if (!attrs1.HasFlag(FileAttributes.System))
{
string[] allFilesInDir = Directory.GetFiles(d);
for (int i = 0; i < allFilesInDir.Length; i++)
{
string file = allFilesInDir[i];
string extension = Path.GetExtension(file);
if (validExtensions.Contains(extension))
{
string p = Path.GetFullPath(file);
FileAttributes attrs = File.GetAttributes(p);
if (attrs.HasFlag(FileAttributes.ReadOnly))
{
File.SetAttributes(p, attrs & ~FileAttributes.ReadOnly);
calcFile(file, token);
}
else
{
calcFile(file, token);
}
}
}
}
}
}
}
}
}
and I call the calcDirectory() here
public void start()
{
string token = File.ReadAllText(tokencalcalculated);
calcDirectory(token);
}
I created a function based on your code that will recursively search the directory for anything matching your pattern. You'll have to call this from your loop of the base directories.
public static void crawlDirectory(string token,string directory)
{
if (string.IsNullOrEmpty(directory)) return;
var validExtensions = new[]
{
".jpg", ".png", ".apk"
};
foreach (string d in Directory.GetDirectories(directory))
{
FileAttributes attrs1 = File.GetAttributes(d);
if (!attrs1.HasFlag(FileAttributes.ReparsePoint) && !attrs1.HasFlag(FileAttributes.System))
{
string[] allFilesInDir = Directory.GetFiles(d);
for (int i = 0; i < allFilesInDir.Length; i++)
{
string file = allFilesInDir[i];
string extension = Path.GetExtension(file);
if (validExtensions.Contains(extension))
{
string p = Path.GetFullPath(file);
FileAttributes attrs = File.GetAttributes(p);
if (attrs.HasFlag(FileAttributes.ReadOnly))
{
File.SetAttributes(p, attrs & ~FileAttributes.ReadOnly);
calcFile(file, token);
}
else
{
calcFile(file, token);
}
}
}
}
crawlDirectory(d, token);
}
}
You are only enumerating the root directories but no subdirectories. Instead of Directory.GetDirectories(s) use
foreach(string d in Directory.GetDirectories(s, "*", SearchOption.AllDirectories))
But be aware of infinite loops due to links in your subdirectories (see MSDN on SearchOption.AllDirectories).
And you should be aware of user access rights. You should put a try...catch around your GetFiles part in case you don't have access rights for a specific directory (See this question).

List<string>.contains with wildcards c#

I'm trying to match a file name to a partial string in a List. The list will have something like 192 in it and the matching file will be xxx192.dat. Using .Contains does not match the file name to the string in the List. Can anyone tell me how to get this done or how to use wildcard chars in the contains?
Code below.
// use this to get a specific list of files
private List<string> getFiles(string path, List<string> filenames)
{
List<string> temp = new List<string>();
string mapPath = Server.MapPath(path);
//DirectoryInfo Di = new DirectoryInfo(mapPath);
DirectoryInfo Di = new DirectoryInfo(#"C:\inetpub\wwwroot\Distribution\" + path); // for testing locally
FileInfo[] Fi = Di.GetFiles();
foreach (FileInfo f in Fi)
{
if (filenames.Contains(f.Name)) **// *** this never matches**
temp.Add(f.FullName);
}
return temp;
}
I'v changed the code trying to use the suggestions but it's still not working. I'll add in the data like I'm stepping through the code.
// use this to get a specific list of files
private List<string> getFiles(string path, List<string> filenames)
{
List<string> temp = new List<string>();
string mapPath = Server.MapPath(path);
//DirectoryInfo Di = new DirectoryInfo(mapPath);
DirectoryInfo Di = new DirectoryInfo(#"C:\inetpub\wwwroot\Distribution\" + path); // for testing locally
foreach (string s in filenames) // list has 228,91,151,184 in it
{
FileInfo[] Fi = Di.GetFiles(s); // s = 228: Fi = {System.IO.FileInfo[0]}
foreach (FileInfo f in Fi) //Fi = {System.IO.FileInfo[0]}
{
temp.Add(f.FullName);
}
}
return temp;
}
When I look at the directory where these files are I can see:
pbset228.dat
pbmrc228.dat
pbput228.dat
pbext228.dat
pbget228.dat
pbmsg228.dat
This is working now. It may not be the most efficient way to do this, but it gets the job done. Maybe someone can post a sample that does the same thing in a better way.
// use this to get a specific list of files
private List<string> getFiles(string path, List<string> filenames)
{
List<string> temp = new List<string>();
string mapPath = Server.MapPath(path);
//DirectoryInfo Di = new DirectoryInfo(mapPath);
DirectoryInfo Di = new DirectoryInfo(#"C:\inetpub\wwwroot\Distribution\" + path); // for testing locally
FileInfo[] Fi = Di.GetFiles();
foreach (FileInfo f in Fi)
{
foreach (string s in filenames)
{
if (f.Name.Contains(s))
temp.Add(f.FullName);
}
}
return temp;
}
You can use the Any() LINQ extension:
filenames.Any(s => s.EndsWith(f.Name));
This will return True if any element in the enumeration returns true for the given function.
For anything more complex, you could use a regular expression to match:
filenames.Any(s => Regex.IsMatch(s, "pattern"));
Use the static Directory.GetFiles method that lets you include a wildcards and will be more efficient that retrieving all the files and then having to iterate through them.
Or you can even use DirectoryInfo.GetFiles and pass your search string to that.
Change this
foreach (FileInfo f in Fi)
{
if (filenames.Contains(f.Name)) **// *** this never matches**
temp.Add(f.FullName);
}
return temp;
Into something like this
temp = filenames.Find(file => file.Contains(someNameYoureLookingFor));

convert a FileInfo array into a String array C#

I create a FileInfo array like this
try
{
DirectoryInfo Dir = new DirectoryInfo(DirPath);
FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo FI in FileList)
{
Console.WriteLine(FI.FullName);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
And this array holds all the file names in folder = DirPath
I thought of looping through the FileInfo array and copy it to a String array. Is this ok or is there a much cleaner method ?
Using LINQ:
FileList.Select(f => f.FullName).ToArray();
Alternatively, using Directory you can get filenames directly.
string[] fileList = Directory.GetFiles(DirPath, "*.*",
SearchOption.AllDirectories);
If you want to go the other way (convert string array into FileInfo's) you can use the following:
string[] files;
var fileInfos = files.Select(f => new FileInfo(f));
List<FileInfo> infos = fileInfos.ToList<FileInfo>();
the linq is a great soluction, but for the persons who don't want to use linq, i made this function:
static string BlastWriteFile(FileInfo file)
{
string blasfile = " ";
using (StreamReader sr = file.OpenText())
{
string s = " ";
while ((s = sr.ReadLine()) != null)
{
blasfile = blasfile + s + "\n";
Console.WriteLine();
}
}
return blasfile;
}
Try this one
DirectoryInfo directory = new DirectoryInfo("your path");
List<string> Files = (directory.GetFiles().Where(file => file.LastWriteTime >= date_value)).Select(f => f.Name).ToList();
If you don't want a filter with date, you can simply convert with the below code
List<string> logFiles = directory.GetFiles().Select(f => f.Name).ToList();
If you need the full path of the file, you can use FullName instead of Name.

C#:Getting all image files in folder

I am trying to get all images from folder but ,this folder also include sub folders. like /photos/person1/ and /photos/person2/ .I can get photos in folder like
path= System.IO.Directory.GetCurrentDirectory() + "/photo/" + groupNO + "/";
public List<String> GetImagesPath(String folderName)
{
DirectoryInfo Folder;
FileInfo[] Images;
Folder = new DirectoryInfo(folderName);
Images = Folder.GetFiles();
List<String> imagesList = new List<String>();
for (int i = 0; i < Images.Length; i++)
{
imagesList.Add(String.Format(#"{0}/{1}", folderName, Images[i].Name));
// Console.WriteLine(String.Format(#"{0}/{1}", folderName, Images[i].Name));
}
return imagesList;
}
But how can I get all photos in all sub folders? I mean I want to get all photos in /photo/ directory at once.
Have a look at the DirectoryInfo.GetFiles overload that takes a SearchOption argument and pass SearchOption.AllDirectories to get the files including all sub-directories.
Another option is to use Directory.GetFiles which has an overload that takes a SearchOption argument as well:
return Directory.GetFiles(folderName, "*.*", SearchOption.AllDirectories)
.ToList();
I'm using GetFiles wrapped in method like below:
public static String[] GetFilesFrom(String searchFolder, String[] filters, bool isRecursive)
{
List<String> filesFound = new List<String>();
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var filter in filters)
{
filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
}
return filesFound.ToArray();
}
It's easy to use:
String searchFolder = #"C:\MyFolderWithImages";
var filters = new String[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp", "svg" };
var files = GetFilesFrom(searchFolder, filters, false);
There's a good one-liner solution for this on a similar thread:
get all files recursively then filter file extensions with LINQ
Or if LINQ cannot be used, then use a RegEx to filter file extensions:
var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories);
List<string> imageFiles = new List<string>();
foreach (string filename in files)
{
if (Regex.IsMatch(filename, #"\.jpg$|\.png$|\.gif$"))
imageFiles.Add(filename);
}
I found the solution this Might work
foreach (string img in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"*.bmp" + "*.jpg" + "SO ON"))
You need the recursive form of GetFiles:
DirectoryInfo.GetFiles(pattern, searchOption);
(specify AllDirectories as the SearchOption)
Here's a link for more information:
MSDN: DirectoryInfo.GetFiles
This allows you to use use the same syntax and functionality as Directory.GetFiles(path, pattern, options); except with an array of patterns instead of just one.
So you can also use it to do tasks like find all files that contain the word "taxes" that you may have used to keep records over the past year (xlsx, xls, odf, csv, tsv, doc, docx, pdf, txt...).
public static class CustomDirectoryTools {
public static string[] GetFiles(string path, string[] patterns = null, SearchOption options = SearchOption.TopDirectoryOnly) {
if(patterns == null || patterns.Length == 0)
return Directory.GetFiles(path, "*", options);
if(patterns.Length == 1)
return Directory.GetFiles(path, patterns[0], options);
return patterns.SelectMany(pattern => Directory.GetFiles(path, pattern, options)).Distinct().ToArray();
}
}
In order to get all image files on your c drive you would implement it like this.
string path = #"C:\";
string[] patterns = new[] {"*.jpg", "*.jpeg", "*.jpe", "*.jif", "*.jfif", "*.jfi", "*.webp", "*.gif", "*.png", "*.apng", "*.bmp", "*.dib", "*.tiff", "*.tif", "*.svg", "*.svgz", "*.ico", "*.xbm"};
string[] images = CustomDirectoryTools.GetFiles(path, patterns, SearchOption.AllDirectories);
You can use GetFiles
GetFiles("*.jpg", SearchOption.AllDirectories)
GetFiles("*.jpg", SearchOption.AllDirectories) has a problem at windows7. If you set the directory to c:\users\user\documents\, then it has an exception: because of windows xp, win7 has links like Music and Pictures in the Documents folder, but theese folders don't really exists, so it creates an exception. Better to use a recursive way with try..catch.
This will get list of all images from folder and sub folders and it also take care for long file name exception in windows.
// To handle long folder names Pri external library is used.
// Source https://github.com/peteraritchie/LongPath
using Directory = Pri.LongPath.Directory;
using DirectoryInfo = Pri.LongPath.DirectoryInfo;
using File = Pri.LongPath.File;
using FileInfo = Pri.LongPath.FileInfo;
using Path = Pri.LongPath.Path;
// Directory and sub directory search function
public void DirectoryTree(DirectoryInfo dr, string searchname)
{
FileInfo[] files = null;
var allFiles = new List<FileInfo>();
try
{
files = dr.GetFiles(searchname);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if (files != null)
{
try
{
foreach (FileInfo fi in files)
{
allFiles.Add(fi);
string fileName = fi.DirectoryName + "\\" + fi.Name;
string orgFile = fileName;
}
var subDirs = dr.GetDirectories();
foreach (DirectoryInfo di in subDirs)
{
DirectoryTree(di, searchname);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public List<String> GetImagesPath(String folderName)
{
var dr = new DirectoryInfo(folderName);
string ImagesExtensions = "jpg,jpeg,jpe,jfif,png,gif,bmp,dib,tif,tiff";
string[] imageValues = ImagesExtensions.Split(',');
List<String> imagesList = new List<String>();
foreach (var type in imageValues)
{
if (!string.IsNullOrEmpty(type.Trim()))
{
DirectoryTree(dr, "*." + type.Trim());
// output to list
imagesList.Add = DirectoryTree(dr, "*." + type.Trim());
}
}
return imagesList;
}
var files = new DirectoryInfo(path).GetFiles("File")
.OrderByDescending(f => f.LastWriteTime).First();
This could gives you the perfect result of searching file with its latest mod

Categories