Get file name with system IO - c#

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);

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"))
{
...
}

C# File Last Modified time

I am trying to get the last write time of a particular file. This is the code and it works:`
DirectoryInfo DR = new DirectoryInfo(folderPath);
FileInfo[] FR2 = DR.GetFiles("InputData.csv");
var FileLastModified= null;
foreach (FileInfo F1 in FR2)
{
FileLastModified = F1.LastWriteTime;
}
FileLastModified gives me the last write time and I am only interested to find the time of this InputData.csv file. The problem is I do not want to use a for loop and need the write time for just one particular file. Is there a better way to write this without the loop?
You don't have to search through a directory to get a FileInfo - you can construct one directly from the full path. It sounds like you just need:
var fileInfo = new FileInfo(Path.Combine(folderPath, "InputData.csv"));
var lastModified = fileInfo.LastWriteTime;
Yes, you can just pass the path to the file you're interested in to a new FileInfo object.
var fileInfo = new FileInfo(pathToFile);
var fileLastModified = fileInfo.LastWriteTime;

how to compare filenames, then classify uniquely from folder into ListBox if repeated

I have json files that i'm trying to classify so the file names are as such:
inputTestingSetting_test
inputTestingSetting_test1310
inputTestingSetting_test1310_ckf
inputTestingSetting_test1310_ols
inputTestingSetting_test1310_sum
inputTestingSetting_test1311_ckf
inputTestingSetting_test1311_ols
inputTestingSetting_test1311_sum
So the output that i want in the ListBox lbJsonFileNames will be
test
test1310
test1311
currently my codes are
DirectoryInfo dInfo = new DirectoryInfo(tbJSFolder.Text);
FileInfo[] Files = dInfo.GetFiles("*.json");
List<jSonName> jsonName = new List<jSonName>();
foreach (FileInfo file in Files)
{
string filename = Path.GetFileNameWithoutExtension(file.Name);
string[] fileNameSplit = filename.Split('_');
jsonName = new List<jSonName>{
new jSonName(fileNameSplit[0],fileNameSplit[1])
};
for(int i=0;i<jsonName.Count;i++)
{
if(jsonName[i].TestNumber == fileNameSplit[1])
{
lbJsonFileNames.Items.Add(jsonName[i].TestNumber);
}
}
}
so my output for lbJsonFileNames is what i want, however it is repeated. is it possible to just show one? i've tried to put jsonName[i].TestNumber to jsonName[i+1].TestNumber. but failed as it is out of range.
is there a way to read the file names, and then compare it with the previous file name to see if it is the same? and if it is the same, ignore, move on to the next file name, if it's different then it is added into the ListBox
changed my codes to
DirectoryInfo dInfo = new DirectoryInfo(tbJSFolder.Text);
FileInfo[] Files = dInfo.GetFiles("*.json");
List<jSonName> jsonName = new List<jSonName>();
HashSet<string> fileNames = new HashSet<string>();
foreach (FileInfo file in Files)
{
string filename = Path.GetFileNameWithoutExtension(file.Name);
string[] fileNameSplit = filename.Split('_');
fileNames.Add(fileNameSplit[1]);
}
foreach(var value in fileNames)
{
lbJsonFileNames.Items.Add(value);
}
got what i want now thanks all~
Your code basically says to put the following into list box:
test
test1310
test1310
test1310
test1310
test1311
test1311
test1311
Before you add as in lbJsonFileNames.Items.Add(jsonName[i].TestNumber);, check for duplicate first. Maybe you can put that list into a Set variable. Set will automatically remove the duplicate. Then put the Set back to lbJsonFileNames.
[Edit] Sorry there is no Set in dot net. Please use HashSet instead.[/Edit]
Your code did not mention what jSonName class is like and the constructor parameters stand for. However to get your output from your input can be much easier:
string[] all = Directory.GetFiles(tbJSFolder.Text, "*.json")
.Select(x => Path.GetFileNameWithoutExtension(x))
.Select(x => x.Split(new char[] { '_' })[1])
.Distinct().ToArray();
lbJsonFileNames.Items.AddRange(all);

how to convert FileInfo object to string

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);
}

How to convert FileInfo into FileInfo[]

I have been working on a program that requires a different approach to finish a job using try and catch nested within another try/catch.
For this purpose I have had to create a set of files as strings and then converted them to FileInfo.
IEnumerable<string> paths = null;
foreach (String fil in paths)
FileInfo h = new FileInfo(fil);
So That wasn't so difficult, I require FileInfo to be in the form of a FileInfo[] array to continue the program however.
System.IO.FileInfo[] files = null;
Simply put, what is the best method to convert one type to the other, either directly from the string of from the converted FileInfo into a FileInfo array (FileInfo[])?
Yeah or create a single-item array:
FileInfo[] files = new FileInfo[] { info };
Why not directly?
paths.Select(p => new FileInfo(p)).ToArray();
Use:
var result = paths.Select(p => new FileInfo(p)).ToArray();
You could just use Linq select to create your FileInfo[]
IEnumerable<string> paths = null; // assuming you are going to fill this with filenames
FileInfo[] fileInfos = paths.Select(p => new FileInfo(p)).ToArray();

Categories