in c# how to get filenames in dropdown without the full path - c#

I want the list of files in a folder to be populated into my dropdown list.
in c# i use this to get filenames into dropdown:
private void CasparRefresh_Click(object sender, EventArgs e)
{
string[] fileArray = Directory.GetFiles(#"C:\Users\JoZee\Desktop\Energy\Caspar\Server\media\");
foreach (string name in fileArray)
{
cbxV1.Items.Add(name);
}
How to i get only the filenames without the full path

You can use Path.GetFileName() method on the output of Directory.GetFiles()
string[] fileArray = Directory.GetFiles(#"C:\Users\JoZee\Desktop\Energy\Caspar\Server\media\");
foreach (string name in fileArray)
{
cbxV1.Items.Add(Path.GetFileName(name));
}

There is another option to do same:
var dirInfo = new DirectoryInfo(#"C:\Users\JoZee\Desktop\Energy\Caspar\Server\media\");
foreach (var fileInfo in dirInfo.GetFiles())
{
cbxV1.Items.Add(fileInfo.Name);
}

Related

FIND A SPECIFIC FILE IN A FOLDER "C:\TEST" THAT CONTAINS MULTIPLE ARCHIVES ".ZIP" USING C#

I have a folder "c:\test" which contains multiple archives. How do I search through all the archives in this folder for a specific file.
This only search a particular archive using ZipPath:
private void button1_Click(object sender, EventArgs e)
{
string zipPath = #"C:\Test\archive1.zip";
string filetosearch = "testfile";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
var position = entry.Name.IndexOf(filetosearch , StringComparison.InvariantCultureIgnoreCase);
if (position > -1)
{
listView1.Items.Add(entry.Name);
}
}
}
}
Is it possible to search all the archives in this folder i.e archive1 to archive70
You can use the following code:
foreach(var zipPath in Directory.GetFiles("C:\\Test"))
{
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
var position = entry.Name.IndexOf(filetosearch , StringComparison.InvariantCultureIgnoreCase);
if (position > -1)
{
listView1.Items.Add(entry.Name);
}
}
}
}
The code gets all the files in the directory and iterates through them. If you need to filter the files by extension you can check it inside the foreach loop.
You probably want something along the lines of
string[] filePaths = Directory.GetFiles(#"c:\Test\", "*.zip")
Then change you click code to
foreach(var filePath in filePaths){
//your code here for each path
}
You may use following code
string[] filePaths = Directory.GetFiles(#"c:\test", "*.zip");
string filetosearch = "testfile";
foreach (var item in filePaths)
{
string name = Path.GetFileName(item);
if (name.IndexOf(filetosearch, StringComparison.InvariantCultureIgnoreCase) != -1)
{
//item is path of that file
}
}

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 strip the full path using file info in 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;
}

deleting folder and subfolders in c#

I have a folder that contains sub folders and files with read only attribute (both files and folders). I want to delete this folder with sub-folders and files.
I wrote this code:
static void Main(string[] args)
{
DirectoryInfo mm = new DirectoryInfo(#"c:\ex");
string aa = Convert.ToString(mm);
string[] allFileNames =
System.IO.Directory.GetFiles(aa,
"*.*",
System.IO.SearchOption.AllDirectories);
string[] alldirNames =
System.IO.Directory.GetDirectories(aa,
"*",
System.IO.SearchOption.AllDirectories);
foreach (string filename in allFileNames)
{
FileAttributes attr = File.GetAttributes(filename);
File.SetAttributes(filename, attr & ~FileAttributes.ReadOnly);
}
foreach (string dirname in alldirNames)
{
FileAttributes attr = File.GetAttributes(dirname);
File.SetAttributes(dirname, attr & ~FileAttributes.ReadOnly);
Directory.Delete(dirname , true);
}
FileInfo[] list = mm.GetFiles();
foreach (FileInfo k in list)
{
k.Delete();
}
mm.Delete();
Console.ReadKey();
}
The problem now is that whenever I run the program it gives me the following error:
Could not find a part of the path 'c:\ex\xx\bb'.
What does this error mean?
Directory.Delete(path, true);
Documentation
The previous answer might work, but I believe it will occur with problems in ReadOnly files. But to ensure the deletion and removal of any attribute ReadOnly, the best way to perform this procedure you must be using a method to facilitate the way you were doing, you were not using the correct properties of objects, for example, when using
DirectoryInfo.ToString ()
and use the
DirectoryInfo.GetFiles (aa ...
you were not using the resources the Framework offers within the DirectoryInfo class. See below:
void DirectoryDelete(string strOriginalPath)
{
DirectoryInfo diOriginalPath = new DirectoryInfo(strOriginalPath);
if (diOriginalPath.Attributes.HasFlag(FileAttributes.ReadOnly))
diOriginalPath.Attributes &= ~FileAttributes.ReadOnly;
string[] lstFileList = Directory.GetFiles(strOriginalPath);
string[] lstdirectoryList = Directory.GetDirectories(strOriginalPath);
if (lstdirectoryList.Length > 0)
{
// foreach on the subdirs to the call method recursively
foreach (string strSubDir in lstdirectoryList)
DirectoryDelete(strSubDir);
}
if (lstFileList.Length > 0)
{
// foreach in FileList to be delete files
foreach (FileInfo fiFileInDir in lstFileList.Select(strArquivo => new FileInfo(strArquivo)))
{
// removes the ReadOnly attribute
if (fiFileInDir.IsReadOnly)
fiFileInDir.Attributes &= ~FileAttributes.ReadOnly;
// Deleting file
fiFileInDir.Delete();
}
}
diOriginalPath.Delete();
}
EmptyFolder(new DirectoryInfo(#"C:\your Path"))
Directory.Delete(#"C:\your Path");
private void EmptyFolder(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
EmptyFolder(subfolder);
}
}

Retrieving Only File Name from a Directory

Using Directory class library I am trying to retrieve all files Name existing in a Folder as below:
private void button1_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(#"d:\Images\", "*.png");
foreach (string img in filePaths)
{
listBox1.Items.Add(img.ToString());
}
}
As you know this method returns Full path and name of the file but I need to get ONLY the name of files.Is it possible to do this in Directory Class? Do I have to use the Path class for this? if yes, how I can assign a path to a variable without file name?
Thanks,
Try this:
using System.IO;
...
private void button1_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(#"d:\Images\", "*.png");
foreach (string img in filePaths)
{
listBox1.Items.Add(Path.GetFileName(img));
}
}
you can use Path.GetFileName method
var file = Path.GetFileName(img);
You can use
var files = Directory.EnumerateFiles(path,searchpattern);
var files = Directory.EnumerateFiles(#"C:\Users\roberth\Programming_Projects\Common\UI\bin\Debug\",
"*.xml");
var filename = new List<string>();
Console.WriteLine("Parsing Files...");
foreach (var file in files)
{
filename.Add(file);
Console.WriteLine("Parsing file: " + file);
....
Use DirectoryInfo instead of Directory. It returns a FileInfo which you can get the Name property of.
private void button1_Click(object sender, EventArgs e)
{
var filePaths = new DirectoryInfo.GetFiles(#"d:\Images\", "*.png").Select(x => x.Name);
foreach (string img in filePaths)
{
listBox1.Items.Add(img.ToString());
}
}
From MSDN
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);
// This code produces output similar to the following:
//
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext'
// GetFileName('C:\mydir\') returns ''
string aPath= #"course\train\yes\";
var fileNames=Directory.GetFiles(aPath).Select(name=>Path.GetFileName(name)).ToArray();

Categories

Resources