how to convert FileInfo object to string - c#

i am picking txt files from a folder in that i am ordering those file according to their respective modify date after ordering these files i've to read contents of each one by one. what will be the possible solution for this. cause i am not able convert FileInfo object to string following is the snippet.
in output : i want all files sorted according to modified date and want to read it one by one.
thanks
string sourcePath = #"C:\sample\*.log";
DirectoryInfo dir = new DirectoryInfo(sourcePath);
FileInfo[] files = dir.GetFiles(sourcePath).OrderBy(order => order.LastWriteTime).ToArray();
foreach (var item in files)
{
listBox1.items.Add(item)
}

Use File.ReadAllText and FileInfo.FullName property to get the path :
listBox1.items.Add(File.ReadAllText(item.FullName));
If you are only looking to get FileName of the file then use FileInfo.Name property like:
listBox1.items.Add(item.Name);
If you are looking to get file path then use FileInfo.FullName like:
listBox1.items.Add(item.FullName);

use the method File.ReadAllText to read each file.
string sourcePath = #"C:\sample\*.log";
DirectoryInfo dir = new DirectoryInfo(sourcePath);
FileInfo[] files = dir.GetFiles(sourcePath).OrderBy(order => order.LastWriteTime).ToArray();
foreach (var item in files)
{
string filecontent = File.ReadAllText(item.FullName);
//do your job here
......
listBox1.items.Add(item.Name);
}

Related

C# get Files from directory with specific CreationTime

i am writing a short code to move files from one directory to another. My code is simple, working fine and looks like this:
public void copy()
{
string sourcePath = #"/Users/philip/Desktop/start";
string destinationPath = #"/Users/philip/Desktop/Ziel";
string[] files = Directory.GetFiles(sourcePath)
foreach (string s in files)
{
string fileName = System.IO.Path.GetFileName(s);
string destFile = System.IO.Path.Combine(destinationPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
The Programm gets all files from the sourcepath and combines the targetpath in the foreach loop vor every file, containing of target path and filename. Then it moves it. Everything works fine.
My aim is now, not to store all files from my directory into the string array. I only want to get the files that have CreationTime after 01.07.2021. Is there an easy and quick way to do it?
I already used this to get the files, but it specifies a singular date and not all files after a specific date:
var files = Directory.GetFiles(sourcePath).Where(x => new FileInfo(x).CreationTime.Date == DateTime.Today.Date);
I would be glad if you could help me out.
Best regards,
Liam
If you want to avoid having to check the creation date on every single FileInfo you can order your files. Like so:
var directory = new DirectoryInfo(sourcePath);
var fileInfos = directory.GetFiles().OrderByDescending(fileInfo => fileInfo.CreationDate);
var result = new List<FileInfo>();
foreach (var fileInfo in fileInfos)
{
if (fileInfo.CreationDate >= DateTime.Today)
result.Add(fileInfo);
else
break; // We can break early, because we ordered our dates descending
// meaning every date after this one is smaller
}
This has upsides and downsides, ordering a huge collection of files could take longer than "just" simply iterating over all and comparing the dates, but you'll need to benchmark it on your own
You could use FileInfo
FileInfo fileInfo = new(s);
if (fileInfo.CreationTime >= DateTime.Parse("01/07/2021"))
{
...
}

Get file extensions to populate into a ComboBox in C#

So I have a folder with some imagens in many extensions like .ico, .png, .jpg, etc. and I've populated it into a comboBox using this code:
string caminho = #"C:\Users\User1\Desktop\Test\";
DirectoryInfo dir = new DirectoryInfo(caminho);
FileInfo[] fi = dir.GetFiles();
foreach (var ficheiro in fi)
{
string caminhoF = caminho + ficheiro.ToString();
string extension = Path.GetExtension(caminhoF);
comboBox1.Items.Add(extension);
}
The code is getting all the existing extensions in this path and put it on the comboBox, but it displays like this:
.ico
.ico
.ico
.png
.png
.jpg
.jpg
and I want to simply display each one of the existing extensions like grouping them.
Could you help me with that?
You can get the file extension from the FileInfo. You can also use Linq Distinct() to get unique extensions.
string caminho = #"C:\Users\User1\Desktop\Test\";
DirectoryInfo dir = new DirectoryInfo(caminho);
var extensions = dir.GetFiles().Select(fi => fi.Extension).Distinct();
foreach (var extension in extensions) {
comboBox1.Items.Add(extension);
}
Ok, I was to find a solution for it. Here it is the code:
string caminho = #"C:\Users\User1\Desktop\Test\";
DirectoryInfo dir = new DirectoryInfo(caminho);
FileInfo[] fi = dir.GetFiles();
foreach (var ficheiro in fi)
{
string caminhoF = caminho + ficheiro.ToString();
string extension = Path.GetExtension(caminhoF);
if (!comboBox1.Items.Contains(extension))
{
comboBox1.Items.Add(extension);
}
}
LINQ-to-Objects makes this easy. LINQ is similar to SQL but allows chaining transformations.
var comboBox1 = new ComboBox();
var caminho = #"C:\Users\User1\Desktop\Test\";
var dir = new DirectoryInfo(caminho);
var extensions = dir.GetFiles()
.Select(fi => fi.Extension)
.OrderBy(ext => ext, StringComparer.CurrentCulture)
.Distinct(StringComparer.CurrentCultureIgnoreCase)
.ToArray();
comboBox1.Items.AddRange(extensions);
Here are the rough steps:
Scan your folder to find out what files it contains.
Extract the file extension from each file you find.
Using a data structure that stores only unique entries, add extensions that you find to be new to the structure.
Iterate over the data structure to populate your combobox.
The part that you need is to find a data structure that helps you store unique values.
HashSet<T> has your back here: it allows quick lookups to determine set membership ("does the set already contain some element x?").
string caminho = #"C:\Users\User1\Desktop\Test\";
DirectoryInfo dir = new DirectoryInfo(caminho);
FileInfo[] fi = dir.GetFiles();
HashSet<string> extensions = new HashSet<string>;
foreach (var ficheiro in fi)
{
string caminhoF = caminho + ficheiro.ToString();
string extension = Path.GetExtension(caminhoF);
// If the set does not contain this extension, it'll be added and
// `Add()` will return true. Otherwise, it will do nothing and `Add()`
// will return false.
extensions.Add( extension );
}
foreach( var extension in extensions ) {
comboBox1.Items.Add(extension);
}

Searching with System.IO.Directory.GetFiles and wildcards in path

I have a curious problem in a C#-program.
I have some local folderpaths like
"C:\test\AB_Systems\ELEGANCE\CB-DOC\live\M7-091.249.99.XX.01\extobjects".
Now i want to search for PDF-files in the subfolder called "extobjects".
Unfortunately there are many subfolders in the folder "live", which got a subfolder called "extobjects", so i thought it would be better to use a wildcard in the searchpath like that:
"C:\test\AB_Systems\ELEGANCE\CB-DOC\live\*\extobjects"
But this doesn't work.
Is there a way do do this?
public static FileInfo[] findFile(String whereToSearch, String searchFor , String mode)
{
IEnumerable<FileInfo> files = null;
if (mode.Equals(""))
mode = "s";
if (searchFor.Equals(""))
searchFor = "*";
if (mode.Equals("r") || mode.Equals("recursive"))
{
DirectoryInfo dir = new DirectoryInfo(whereToSearch);
files = dir.EnumerateFiles(searchFor, searchOption: SearchOption.AllDirectories);
}
if (mode.Equals("s") || mode.Equals("specific"))
{
DirectoryInfo dir = new DirectoryInfo(whereToSearch);
files = dir.EnumerateFiles(searchFor, searchOption: SearchOption.TopDirectoryOnly);
}
if (files != null) return files.ToArray<FileInfo>();
else return null;
}
That's an example how to do it.
It's important to say that only the filename can contain a wildcard pattern like *. The Path can be given as where to start the search and by giving searchOption: searchOption.AllDirectories as an argument it will go through all sub-directories of the entry path.
You will receive an Array of FileInfo which objects that contain the the path and more information.
You can use Linq like this:
var files = Directory
.EnumerateDirectories(#"C:\test\AB_Systems\ELEGANCE\CB-DOC\live", "extobjects", SearchOption.AllDirectories)
.SelectMany(x => Directory.EnumerateFiles(x, "*pdf", SearchOption.TopDirectoryOnly))
.ToArray();
I'd choose a solution exactly what BugFinder proposed, you could optimize the following foreach-loop into a LINQ query if your .NET target supports it.
// Itterate subdirectories of the live folder
foreach (var subDir in Directory.GetDirectories(#"C:\test\AB_Systems\ELEGANCE\CB-DOC\live"))
{
// Check if path to extobjects exists
var extObjects = Path.Combine(subDir, "extobjects");
if (Directory.Exists(extObjects))
{
var pdfFiles = Directory.GetFiles(extObjects, "*").Where(x=>x.EndsWith(".pdf"));
// Do something with the pdf file paths
}
}

How can i get from a FileInfo[] the file full name full directory including the file extension?

This is the code:
FileInfo[] flist = d.GetFiles();
if (flist.GetLength(0) > 0)
{
foreach (FileInfo txf in flist)
{
string fn = txf.FullName + txf.Extension;
}
}
If i'm doing only fullname it will give me the directory+file name but without the Extension.
And if i'm doing it: string fn = txf.FullName + txf.Extension; Extension is empty ""
I need to get it full like this for exmaple: c:\test.png
Or that fn will contain: c:\temp\dir\testing.jpg
Full directory path + full file name + the file name extension
According to the documentation, FullName field of a FileInfo object includes full path, file name and file extension (FileInfo inherits FullName from FileSystemInfo). So it is more like the code, which is in charge for creating these files, is not appending the proper extension (Assuming d is a DirectoryInfo and not other - maybe homemade - class).

Get file name with system IO

I'm working on a C# script that has to access a random file during runtime, the problem is that the files are being generated on the fly by another source and I have no means of knowing their names, I have solved a first issue which is to get how many files there are in my working directory:
s = #"C:\Imagenes";
System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(s);
int files;
files = d.GetFiles().Length;
Debug.Log(files.ToString());
return files;
Now I would like to acces a random element in my working dicrectory, but since I don't have a clue what their names are, is there a way to get their names by index or something?
DirectoryInfo.GetFiles will give you array of fileInfo objects. From that you can get the file name using FileInfo.Name
You need to use the FileInfo objects that are returned by d.GetFiles():
DirectoryInfo d = new DirectoryInfo("c:\\path");
foreach (FileInfo file in d.GetFiles())
{
string name = file.Name;
}
try
FileInfo[] fileinfos = d.GetFiles();
foreach (FileInfo FI in fileinfos)
{
string fullname = FI.FullName;
string name = FI.Name;
// do someting...
}
see
http://msdn.microsoft.com/en-us/library/4cyf24ss.aspx
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx
Not sure why you want a random file, but this should work (except files get deleted during calculation of length and getting a rondom one)
int length = d.GetFiles().Length;
Random rnd = new Random();
var randomFile = d.GetFiles().ElementAt(rnd.Next(0, length-1);

Categories