C# FileInfo Array to String Array - c#

I have an array that stores files from a directory:
string pathToDirectory = #"C:\files";
System.IO.DirectoryInfo diDir = new DirectoryInfo(pathToDirectory);
System.IO.FileInfo[] File_Array = diDir.GetFiles();
foreach (FileInfo lfileInfo in File_Array)
{
}
I want to try and convert this array into a string type array instead of a FileInfo type. Please let me know how I can go about doing this. Any help would be greatly appreciated.

Use static Directory class instead. It returns files as strings instead of instantiating FileInfo instances which you don't need
string[] files = Directory.GetFiles(pathToDirectory);
If you want just file names without path, then use Path to get rid of directory path:
var fileNames = Directory.GetFiles(pathToDirectory)
.Select(Path.GetFileName);

string[] fileNames = File_Array.Select(f => f.Name).ToArray();

Related

How to create a folder out of the first few letters of a filename?

So I checked out the basic things but I'd like to do the following:
I have 5 files let's say: X1_word_date.pdf, XX1_word_date.pdf, etc...
I'd like to create a folder structure like: C:\PATH\X1, C:\PATH\XX1, etc...
So how do I take the first letters before the '_' in the file names and put it into a string?
My idea is that I use the Directory.CreateDirectory and than combine the main path and the strings so I get the folders.
How do I do that? Help appreciated.
string fileName = "X1_word_date.pdf";
string[] tokens = fileName.Split('_');
string myPath = "C:\\PATH\\";
Directory.CreateDirectory( myPath + tokens[0]);
Something like this should work. Using Split() will also allow for numbers greater than 9 to be dealt with
Supposed that your files is a List<string> which contains the file name (X2_word_date.pdf,...)
files.ForEach(f => {
var pathName= f.Split('_').FirstOrDefault();
if(!string.IsNullOrEmpty(pathName))
{
var directoryInfo = DirectoryInfo(Path.Combine(#"C:\PATH", pathName));
if(!directoryInfo.Exists)
directoryInfo.Create();
//Then move this current file to the directory created, by FileInfo and Move method
}
})
With simple string methods like Split and the System.IO.Path class:
var filesAndFolders = files
.Select(fn => new
{
File = fn,
Dir = Path.Combine(#"C:\PATH", Path.GetFileNameWithoutExtension(fn).Split('_')[0].Trim())
});
If you want to create that folder and add the file:
foreach (var x in filesAndFolders)
{
Directory.CreateDirectory(x.Dir); // will only create it if it doesn't exist yet
string newFileName = Path.Combine(x.Dir, x.File);
// we don't know the old path of the file so i can't show how to move
}
Or using regex
string mainPath = #"C:\PATH";
string[] filenames = new string[] { "X1_word_date.pdf", "X2_word_date.pdf" };
foreach (string filename in filenames)
{
Match foldernameMatch = Regex.Match(filename, "^[^_]+");
if (foldernameMatch.Success)
Directory.CreateDirectory(Path.Combine(mainPath, foldernameMatch.Value));
}
Using the bigger picture starting with only your Source and Destination directory.
We can list all files we need to move with Directory.GetFiles.
In this list We first isolate the filename with GetFileName.
Using simple String.Split you have the new directory name.
Directory.CreateDirectory will create directories unless they already exist.
To move the file we need its destination path, a combinaison of the Destination directory path and the fileName.
string sourceDirectory = #"";
string destDirectory = #"";
string[] filesToMove = Directory.GetFiles(sourceDirectory);
foreach (var filePath in filesToMove) {
var fileName = Path.GetFileName(filePath);
var dirPath = Path.Combine(destDirectory, fileName.Split('_')[0]);
var fileNewPath= Path.Combine(dirPath,fileName);
Directory.CreateDirectory(dirPath);// If it exist it does nothing.
File.Move(filePath, fileNewPath);
}

C# get a textfile from EACH folder,

I have a folder structure similar to this:
HostnameA->DateTimeA->hashdumpDateTimeA.txt
HostnameA->DateTimeB->hashdumpDateTimeB.txt
HostnameA->DateTimeC->hashdumpDateTimeC.txt
HostnameA->DateTimeD->hashdumpDateTimeD.txt
My Goal:
Given a folder(in this case HostnameA) i need to:
1) Get each hashdumpDateTime.txt filename and place it in a String array -Assumed the file always exist in all folder-
2) Generate DropDownBox using the array (I can figure this out)
3) When user selects a filename via dropdownbox, it will fill my datagridview with the
contents (I can figure this out)
So my problem really is the #1 since i don't know how to make a loop to check the filename coming from a HostnameA folder, I need to know this since the DateTime of these filenames changes
I really appreciate the future help, thanks and cheers =)
You can use Directory.GetFiles method
var files = Directory.GetFiles("directoryPath","*.txt",SearchOption.AllDirectories)
That will give you all file names.If you don't want just names for example if you want file's full path, and some other attributes (like CreationTime, LastAccessTime) use DirectoryInfo class
DirectoryInfo di = new DirectoryInfo("path");
var files = di.GetFiles("*.txt",SearchOption.AllDirectories)
That will return an array of FileInfo instances.Then use a loop and do what you want with the files.
You doesn't need to know the exact name of DirectoryName or FileName, using a for loop and a searchPattern instead.
private string[] GetFileNames(string folder)
{
var files = new List<string>();
foreach (var dateTimeFolder in Directory.GetDirectories(folder))
{
files.AddRange(Directory.GetFiles(dateTimeFolder, "hashdump*.txt"));
}
return files.ToArray();
}

how do i read the filenames inside the directory to an array

(i am using C# windows application)
i want to read all the FileNames of a directory to an array.. how do i read that..
( suppose consider a directory with a names ROOT,ROOT2
Let ROOT1 has a.txt,b.txt,c.txt
let ROOT2 has x.txt,y.txt,z.txt
i just want to read those things to my array ...
what is the way to read that...? ( or ) can you send me the code for that...?
If there are sub folders you want
string[] oFiles = Directory.GetFiles(sPath, "*", SearchOption.AllDirectories);
otherwise you want
string[] oFiles = Directory.GetFiles(sPath);
or if you want to filter you want
string[] oFiles = Directory.GetFiles(sPath, "*");
To filter by .txt extension replace * with *.txt as the second argument.
This is some code to read the files in a directory:
DirectoryInfo di = new DirectoryInfo("c:/root1");
FileInfo[] rgFiles = di.GetFiles("*.*");
foreach(FileInfo fi in rgFiles)
{
Response.Write("<br>" + fi.Name + "");
}
FileInfo is a string array containing all files.
string[] fileNames = Directory.GetFiles(directoryPath, "*", SearchOptions.AllDirectories)
A call to Directory.GetFiles(directoryPath) is what you want. If you want to go deeper into the structure of the path (get files in subfolders, etc) then qualify the call with SearchOptions.AllDirectories, or try looking here

Determine number of files in a directory

I need to determine the number of files/subdirectories in a directory. I don't care which files/directories are actually in that directory. Is there a more efficient way than using
_directoryInfo.GetDirectories().Length +
_directoryInfo.GetFiles().Length
Thanks.
That's probably about as good as it gets, but you should use GetFileSystemInfos() instead which will give you both files and directories:
_directoryInfo.GetFileSystemInfos().Length
string[] filePaths = Directory.GetFiles(#"c:\MyDir\");
then just take the size of the filePaths array
code from:
C#-Examples
You could use the GetFileSystemEntries method found in the Directory class and then query the Length of the array of items returned.
DirectoryInfo d = new DirectoryInfo(#"C:\MyDirectory\");
FileInfo[] files = d.GetFiles("*.*");
int NumberOfFilesInDir;
foreach( FileInfo file in files )
{
NumberOfFilesInDir++;
}

Parse directory name from a full filepath in C#

If I have a string variable that has:
"C:\temp\temp2\foo\bar.txt"
and I want to get
"foo"
what is the best way to do this?
Use:
new FileInfo(#"C:\temp\temp2\foo\bar.txt").Directory.Name
Far be it for me to disagree with the Skeet, but I've always used
Path.GetFileNameWithoutExtension(#"C:\temp\temp2\foo\bar.txt")
I suspect that FileInfo actually touches the file system to get it's info, where as I'd expect that GetFileNameWithoutExtension is only string operations - so performance of one over the other might be better.
I think most simple solution is
DirectoryInfo dinfo = new DirectoryInfo(path);
string folderName= dinfo.Parent.Name;
Building on Handleman's suggestion, you can do:
Path.GetFileName(Path.GetDirectoryName(path))
This doesn't touch the filesystem (unlike FileInfo), and will do what's required. This will work with folders because, as the MSDN says:
Return value: The characters after the last directory character in path. If the last
character of path is a directory or volume separator character, this
method returns String.Empty. If path is null, this method returns
null.
Also, looking at the reference source confirms that GetFilename doesn't care if the path passed in is a file or a folder: it's just doing pure string manipulation.
I had an occasion when I was looping through parent child directories
string[] years = Directory.GetDirectories(ROOT);
foreach (var year in years)
{
DirectoryInfo info = new DirectoryInfo(year);
Console.WriteLine(info.Name);
Console.WriteLine(year);
//Month directories
string[] months = Directory.GetDirectories(year);
foreach (var month in months)
{
Console.WriteLine(month);
//Day directories
string[] days = Directory.GetDirectories(month);
foreach (var day in days)
{
//checkes the files in the days
Console.WriteLine(day);
string[] files = Directory.GetFiles(day);
foreach (var file in files)
{
Console.WriteLine(file);
}
}
}
}
using this line I was able to get only the current directory name
DirectoryInfo info = new DirectoryInfo(year);
Console.WriteLine(info.Name);
It'll depend on how you want to handle the data, but another option is to use String.Split.
string myStr = #"C:\foo\bar.txt";
string[] paths = myStr.Split('\\');
string dir = paths[paths.Length - 2]; //returns "foo"
This doesn't check for an array out of bounds exception, but you get the idea.

Categories

Resources