How to strip the full path using file info in C# - c#

I am new to C# programming.Please suggest me how to retrieve the fullpath but using only file.Name in my code as I only want to enter file name in my listBox not full path
My code is:
listBox1.DataSource = GetFolder("..\\video\\");
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
foreach (FileInfo file in allFiles)
{
FileList.Add(file.FullName);
}
return FileList;
}

FileInfo(path).Directory.FullPath
Your actual problem of your code is missing semi-colon for this line
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
It should be
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories);

If I get you right, you want the FullPath as value but only the FileName displayed. To achieve this, you could use a List of FileInfos containing both of these values and tell the ListBox, which member is the value and which one should be displayed:
this.listBox1.DisplayMember = "Name";
this.listBox1.ValueMember = "FullName";
listBox1.DataSource = GetFolder("..\\video\\");
Player.URL = Convert.ToString(listBox1.SelectedValue); // Instead of SelectedItem
private static List<FileInfo> GetFolder(string folder)
{
List<FileInfo> fileList = new List<FileInfo>();
foreach (FileInfo file in new DirectoryInfo(folder).GetFiles("*.mpg", SearchOption.AllDirectories))
{
fileList.Add(file);
}
return fileList;
}

FileList.Add(file.FullName);
Please Change this line like below
FileList.Add(file.Name );

listBox1.DataSource = GetFolder("..\\video\\");
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
foreach (FileInfo file in allFiles)
{
FileList.Add(file.Name);
}
return FileList;
}

Related

How to get the names of a subfolder in c#

I have a folder path with me something like "c:/videos". it contains subfolders like car, bike, bus ... etc. need to get only the sub folder name and store in a string array.
And please note i don't need a full sub folder path
out needed like:- car, bike, bus
not like c:/videos/car
c:/videos/bike
c:/videos/bus
You have to iterate over the SubDirectories.
And replace the startpath c:\videoswith an empty string:
var rootDir = #"c:\videos";
DirectoryInfo directoryInfo = new DirectoryInfo(rootDir);
var dirs = new System.Collections.Generic.List<string>();
foreach (var dir in directoryInfo.GetDirectories())
{
dirs.Add(dir.Name.Replace($"{rootDir}\\", ""));
}
var result = dirs.ToArray();
You can use GetDirectories method
var directories = Directory.GetDirectories(#"c:/videos");
this will give you a string array of all the subdirectories and then you can call Path.GetDirectoryName() to get the folder name
List<string> subfolders = List<string>();
var directories = Directory.GetDirectories(#"c:/videos");
foreach(var directory in directories)
{
subfolders.Add(Path.GetDirectoryName(directory));
}
var result = subfolders.ToArray();
string yourPath= #"C:\videos";
// Get all subdirectories
string[] subDirs = Directory.GetDirectories(root);
foreach (string subdirectory in subdirectoryEntries)
LoadSubDirs(subdirectory);
List<string> subfolders = List<string>();
private void LoadSubDirs(string dir)
{
subfolders.Add(Path.GetDirectoryName(dir));
string[] subdirectoryEntries = Directory.GetDirectories(dir);
foreach (string subdirectory in subdirectoryEntries)
{
LoadSubDirs(subdirectory);
}
}

Stepping through directories and sub-directories

I have code that steps through a main directory and all the sub directories. The images in each sub directories needs to be renamed as per the folder it is ins name.
C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\\Batch002-190227010418829\PPA14431564096\File1.png
should rename to
C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\Batch002-190227010418829\PPA14431564096\PPA14431564096.png
I can see the code is stepping through every thing but the image isn't beeing renamed and I can't see where I went wrong
while(isTrue)
{
try
{
//write your code here
string filename1 = "1.tif";
string newFileName = "allen.tif";
string[] rootFolder = Directory.GetDirectories(#"C:\Users\alle\Desktop\BillingCopy");
foreach(string dir in rootFolder)
{
string[] subDir1 = Directory.GetDirectories(dir);
foreach(string subDir in subDir1)
{
string[] batchDirList = Directory.GetDirectories(subDir);
foreach(string batchDir in batchDirList)
{
string[] waybillNumberDir = Directory.GetDirectories(batchDir);
foreach(string hawbDir in waybillNumberDir)
{
string waybillNumber = Path.GetDirectoryName(hawbDir);
string[] getFileimages = Directory.GetFiles(hawbDir);
foreach(string imgInDir in getFileimages)
{
File.Copy(imgInDir, Path.Combine(#"C:\Users\alle\Desktop\Copy", string.Format("{0}.{1}", waybillNumber, Path.GetExtension(imgInDir))));
}
}
}
}
}
File.Copy(Path.Combine("source file", filename1), Path.Combine("dest path",
string.Format("{0}{1}", Path.GetFileNameWithoutExtension(newFileName), Path.GetExtension(newFileName))), true);
}
catch { }
}
When querying you can try using Linq to obtain the required data:
// All *.png files in all subdirectories
string rootDir = #"C:\Users\alle\Desktop\BillingCopy";
var agenda = Directory
.EnumerateFiles(rootDir, "*.png", SearchOption.AllDirectories)
.Select(file => new {
oldName = file,
newName = Path.Combine(
Path.GetDirectoryName(file),
new DirectoryInfo(Path.GetDirectoryName(file)).Name + Path.GetExtension(file))
})
.ToArray();
Then we can move (not copy) the files:
foreach (var item in agenda)
File.Move(item.oldName, item.newName);

How to convert FileInfo to FileInfo[] on string[]?

I resolved my problem. But error when I was create constructor LI variable is ListViewItem but I can use this in foreach loop?.
ListViewItem LISTA = default(ListViewItem);
foreach (LISTA in this.lstImgAdded.SelectedItems) {
I'm trying to get Length of the list file with my code:
string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop, false);
List<FileInfo> fileInfos = new List<FileInfo>();
foreach (string filePath in filePaths)
{
FileInfo f = new FileInfo(filePaths);
fileInfos.Add(f);
This show error like this:
Cannot convert from 'string[]' to 'string'
You cannot convert a class to its exactly identical array of that class. Just use: FileInfo f = new FileInfo(filePath); for your foreach instead
Also, to get the "length of the list of file" will be identical to filePaths.Length
If you need the length, use filePaths.Length instead.
If you want to populate the FileInfo, do this instead:
string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop, false);
List<FileInfo> fileInfos = new List<FileInfo>();
foreach (string filePath in filePaths)
{
FileInfo f = new FileInfo(filePaths);
fileInfos.Add(f);
//long s1 = f.Length;
}
And all your file infos will be in the fileInfos and if you need the amount of item in the list, do it by Count like this: fileInfos.Count
Just change filePaths to filePath in the foreach loop
FileInfo f = new FileInfo(filePath);
An alternative would be change the loop like this:
foreach (int s1 in filePaths.Select(filePath => new FileInfo(filePath)).Select(f => ((FileInfo[]) f).Length))
{
//Do somthing with the s1 here
}

C# retrieving subdirectories from selected directory

I am trying to find a way to retrieve the subfolders from a selected directory. I have used FolderBrowserDialog inside of my code to all the user to select the "root" directory that the program will be using. But I am stuck on how to get the subdirectories from that. I want to plce these subdirectory string names inside an array to be used later. I tried using Directory.getFiles("the selected path"), but this does not display the subdirectories.
Any help is greatly appreciated! Thank you
private void Folderselector_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
listView1.Items.Clear();
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem item = new ListViewItem(fileName);
item.Tag = file;
listView1.Items.Add(item);
}
}
}
Use the method overload with SearchOption.AllDirectories
something like this?
var dirs = new DirectoryInfo(path).GetDirectories("*",SearchOption.AllDirectories)
.Select(d => d.FullName)
.ToList();
and if you want the directory names relative to your root dir
var dirs = new DirectoryInfo(path).GetDirectories("*",SearchOption.AllDirectories)
.Select(d => d.FullName)
.Select(s => new Uri(path).MakeRelative(new Uri(s)).ToString())
.ToList();
Close, but there's a different method for directories:
System.IO.Directory.GetDirectories(string rootDirectory);
System.IO.Directory.GetDirectories(string rootDirectory);
With recursion is your solution
List<string> dirsResult = new List<string>();
public void GetDirectories(string currentDirectory)
{
string[] directories = Directory.GetDirectories(currentDirectory);
foreach(var dir in directories)
{
dirsResult.Add(dir);
GetDirectories(dir);
}
}
I haven't tested it, but something like this should work.

How to get files in the subfolders too from directory

Hi I have to get files from a specified path in the directory. This is the method I wrote but I didn't get the files from the subfolders.
Private void getfiles(){
Directoryinfo info = new Directoryinfo(configurationmanager.appsettings["Targetroot"].tostring ());
if (info.exists){
Gvfiles.datasource = info.GetFiles();
Gvfiles.databind();
}
}
You will want to include the SearchOption.AllDirectories.
Example:
info.GetFiles("*", SearchOption.AllDirectories);
Reference:
http://msdn.microsoft.com/en-us/library/ms143327(v=vs.80).aspx
And:
http://msdn.microsoft.com/en-us/library/ms143448(v=vs.80).aspx
This returns an array of the (immediate) subdirectories:
System.IO.DirectoryInfo ParentDirectory = new System.IO.DirectoryInfo(ParentPath);
System.IO.DirectoryInfo[] DirectoryArr = ParentDirectory.GetDirectories();
I'm sure you can find a way to adapt it to your likings.
DirectoryInfo info = new DrectoryInfo(configurationmanager.appsettings["Targetroot"].tostring ());
//FileInfo[] _files = info.GetFiles("You could set a search pattern");
//FileInfo[] _files = info.GetFiles("*.aspx");
FileInfo[] _files = info.GetFiles();
Gvfiles.datasource = _files;
Gvfiles.databind();
or:
DirectoryInfo info = new DirectoryInfo(Server.MapPath("/"));
DirectoryInfo[] _info = info.GetDirectories();
for (int i = 0; i < _info.Length; i++)
{
FileInfo[] files = _info[i].GetFiles("search pattern");
Gvfiles.datasource = files;
Gvfiles.databind();
}
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}

Categories

Resources