Adding File and Directory to Array - c#

I have this method that searches all files and folders in "C:\Sharing".
string[] fileArray = Directory.GetFiles(#"C:\Sharing", "*.*", SearchOption.AllDirectories);
And foreach shows me full path of each file. Great. However, since these are in a directory called "Sharing", I want to check and add files that are like
C:\Sharing\Jerry2022\wedding.jpg (array: 'wedding.jpg', 'Jerry2022')
C:\Sharing\snapshot.jpg (array: 'snapshot.jpg')
C:\Sharing\Newsletter\cover-june.webp (array: 'cover-june.webp', 'Newsletter')
So as you can see, I want to add file and subdirectory name to a string array or List, doesnt matter. Excluding "Sharing".
How can I split the results? I know I can use Substring and LastIndexOf("\") + 1 and separate the ending '' but I'm not sure how to match up the filename with the subdir name too.
Any help is appreciated

You can use DirectoryInfo to get the information you want:
C#:
var directoryInfo = new DirectoryInfo(#"C:\Sharing");
if (directoryInfo.Exists)
{
foreach (var fileInfo in directoryInfo.GetFiles("*.*", SearchOption.AllDirectories))
{
var fileName = fileInfo.Name;
Console.WriteLine(fileName);
var directoryName = fileInfo.DirectoryName;
// you can use split to get the directory name array
Console.WriteLine(directoryName);
}
}
I found an other way, use Uri for this scenario:
C#:
string[] fileArray = Directory.GetFiles(#"C:\Sharing", "*.*", SearchOption.AllDirectories);
foreach (var s in fileArray)
{
var uri = new Uri(s);
var uriSegments = uri.Segments.ToArray();
}
You will see each part of the full path, but you may need to use .Trim('/') for each part. Then you can use string.Equals to get directories which you want.

You could split the results using Split
But of course you can also work with FileInfo instead

Related

Move files according to searchPattern

I have excel list with file names that I want to move from one folder to another. And I can not just copy paste the files from one folder to another since there are allot of files that do not match the excel list.
private static void CopyPaste()
{
var pstFileFolder = "C:/Users/chnikos/Desktop/Test/";
//var searchPattern = "HelloWorld.docx"+"Test.docx";
string[] test = { "HelloWorld.docx", "Test.docx" };
var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, test.ToString()))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
}
}
I have tried several things but I still think that with a array it would be the easiest way to do it(correct me if I am wrong).
The issue that I face right now is that it can not find any files (there are files under this name.
You can enumerate the files in the directory by using Directory.EnumerateFiles and use a linq expression to check if the file is contained in you string array.
Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d)));
So your foreach would look like
this
foreach (var file in Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d)))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
Actually no, this will not search the directory for pst files. Either build the path yourself using Path.Combine and then iterate over the string-array, or use your approach. With the code above, you need to update the filter, because it will not find any file when given a string[].ToString (). This should do:
Directory.GetFiles (pstFileFolder, "*.pst")
Alternatively, you can iterate over all files without a filter and compare the filenames to your string-array. For this, a List<string> would be a better way. Just iterate over the files like you're doing and then check if the List contains the file via List.Contains.
foreach (var file in Directory.GetFiles (pstFileFolder))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Here, either iterate over the string array or use a List
if (!nameList.Contains (theFileInfo.Name)) continue;
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
I think you need this
var pstFileFolder = "C:/Users/chnikos/Desktop/Test/";
//var searchPattern = "HelloWorld.docx"+"Test.docx";
string[] test = { "HelloWorld.docx", "Test.docx" };
var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/";
// Searches the directory for *.pst
foreach (var file in test)
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var source = Path.Combine(soruceFolder, theFileInfo.Name);
var destination = Path.Combine(pstFileFolder, file);
if (File.Exists(source))
File.Move(file, destination);
}

How can I fill my combobox with .txt files, but only their name without the path?

string path = AppDomain.CurrentDomain.BaseDirectory;
string[] filePaths = Directory.GetFiles(path, "*.txt");
foreach (string file in filePaths)
{
cboLanden.Items.Add(file);
}
This is my code and it returns the full path, I would like to have only the name, without the path in my combobox.
Use Path.GetFileName() to get file name without path:
string path = AppDomain.CurrentDomain.BaseDirectory;
string[] filePaths = Directory.GetFiles(path, "*.txt");
foreach (string file in filePaths)
{
cboLanden.Items.Add(Path.GetFileName(file));
}
Also consider to use files as data source of your comboBox:
cboLanden.DataSource = Directory.EnumerateFiles(path, "*.txt")
.Select(Path.GetFileName)
.ToList();
Simple just use this
foreach (string file in files)
{
Path.GetFileNameWithoutExtension(file);
}
If there is a file name in files like c:\coolpic.jpg
it will return only coolpic without extension

How can I get all filenames without path in c#

I am using this code
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v));
foreach (string item in filePaths)
{
Response.Write(item);
}
Problem in this code i am getting file name with full path like this
C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\Gallery\GalleryImage\c050\DSC_0865.JPG
I just want file which is "DSC_0865.JPG"
You can use the Path.GetFileName method to get the file name (and extension) of the specified path, without the directory:
foreach (string item in filePaths)
{
string filename = Path.GetFileName(item);
Response.Write(filename);
}
Try using Path.GetFileName:
Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v))
.Select(Path.GetFileName);
You could use the methods in the Path such as GetFileName if you just want the bit without the path.
In your case something like:
foreach(string item in filePaths)
{
Response.Write(Path.GetFileName(item));
}
This is pretty straight forward:
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v));
foreach (string item in filePaths)
{
Response.Write(System.IO.Path.GetFileName(item));
}

How to get file names from the directory, not the entire path

I am using the below method to get the file names. But it returns the entire path and I don't want to get the entire path. I want only file names, not the entire path.
How can I get that only file names not the entire path
path= c:\docs\doc\backup-23444444.zip
string[] filenames = Directory.GetFiles(targetdirectory,"backup-*.zip");
foreach (string filename in filenames)
{ }
You could use the GetFileName method to extract only the filename without a path:
string filenameWithoutPath = Path.GetFileName(filename);
System.IO.Path is your friend here:
var filenames = from fullFilename
in Directory.EnumerateFiles(targetdirectory,"backup-*.zip")
select Path.GetFileName(fullFilename);
foreach (string filename in filenames)
{
// ...
}
Try GetFileName() method:
Path.GetFileName(filename);
You can use this, it will give you all file's name without Extension
List<string> lstAllFileName = (from itemFile in dir.GetFiles()
select Path.GetFileNameWithoutExtension(itemFile.FullName)).Cast<string>().ToList();
Linq is good
Directory.GetFiles( dir ).Select( f => Path.GetFileName( f ) ).ToArray();

Get filenames without path of a specific directory

How can I get all filenames of a directory (and its subdirectorys) without the full path?
Directory.GetFiles(...) returns always the full path!
You can extract the filename from full path.
.NET 3, filenames only
var filenames3 = Directory
.GetFiles(dirPath, "*", SearchOption.AllDirectories)
.Select(f => Path.GetFileName(f));
.NET 4, filenames only
var filenames4 = Directory
.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName); // <-- note you can shorten the lambda
Return filenames with relative path inside the directory
// - file1.txt
// - file2.txt
// - subfolder1/file3.txt
// - subfolder2/file4.txt
var skipDirectory = dirPath.Length;
// because we don't want it to be prefixed by a slash
// if dirPath like "C:\MyFolder", rather than "C:\MyFolder\"
if(!dirPath.EndsWith("" + Path.DirectorySeparatorChar)) skipDirectory++;
var filenames4s = Directory
.EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)
.Select(f => f.Substring(skipDirectory));
confirm in LinqPad...
filenames3.SequenceEqual(filenames4).Dump(".NET 3 and 4 methods are the same?");
filenames3.Dump(".NET 3 Variant");
filenames4.Dump(".NET 4 Variant");
filenames4s.Dump(".NET 4, subfolders Variant");
Note that the *Files(dir, pattern, behavior) methods can be simplified to non-recursive *Files(dir) variants if subfolders aren't important
See Path.GetFileName:
Returns the file name and extension of the specified path string.
The Path Class has several useful filename and path methods.
You want Path.GetFileName
This returns just the filename (with extension).
If you want just the name without the extension then use Path.GetFileNameWithoutExtension
You can just extract the file name from the full path.
var sections = fullPath.Split('\\');
var fileName = sections[sections.Length - 1];
string fileName = #"C:\mydir\myfile.ext";
string path = #"C:\mydir\";
string result;
result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
Although several right answers are there for this questions, You may find this solution as:
string[] files = Directory.EnumerateFiles("C:\Something", "*.*")
.Select(p => Path.GetFileName(p))
.Where(s => s.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)).ToArray();
Thanks
Create a DirectoryInfo object, use a search pattern to enumerate, then treat it like an array.
string filePath = "c:\Public\";
DirectoryInfo apple = new DirectoryInfo(#filepath);
foreach (var file in apple.GetFiles("*")
{
//do the thing
Console.WriteLine(file)
}
You can get the files name of particular directory using GetFiles() method of the DirectoryInfo class.
Here are sample example to list out all file and it's details of particular directory
System.Text.StringBuilder objSB = new System.Text.StringBuilder();
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo("d:\\");
objSB.Append("<table>");
objSB.Append("<tr><td>FileName</td>" +
"<td>Last Access</td>" +
"<td>Last Write</td>" +
"<td>Attributes</td>" +
"<td>Length(Byte)</td><td>Extension</td></tr>");
foreach (System.IO.FileInfo objFile in directory.GetFiles("*.*"))
{
objSB.Append("<tr>");
objSB.Append("<td>");
objSB.Append(objFile.Name);
objSB.Append("</td>");
objSB.Append("<td>");
objSB.Append(objFile.LastAccessTime);
objSB.Append("</td>");
objSB.Append("<td>");
objSB.Append(objFile.LastWriteTime);
objSB.Append("</td>");
objSB.Append("<td>");
objSB.Append(objFile.Attributes);
objSB.Append("</td>");
objSB.Append("<td>");
objSB.Append(objFile.Length);
objSB.Append("</td>");
objSB.Append("<td>");
objSB.Append(objFile.Extension);
objSB.Append("</td>");
objSB.Append("</tr>");
}
objSB.Append("</table>");
Response.Write(objSB.ToString());
This example display list of file in HTML table structure.

Categories

Resources