How to get the item and subItem on the ListViewControl? - c#

How to access the files in ListViewControl?
On an initial event, I have a button that lists the necessary files on the lsitView using foreach loop. The control has 2 items: File Name & File Path (subItem)
DirectoryInfo d = new DirectoryInfo(path);
foreach (FileInfo f in d.GetFiles("*.txt", SearchOption.AllDirectories))
{
lstProjectFiles.Items.Add(f.Name).SubItems.Add(f.DirectoryName.ToString());
}
Now, I would like to display each items' full path plus the filename with extensions.
foreach(ListViewItem f in lstView1.Items)
{
Console.Writeline(f.ToString());
}
When I get the filename, the output is like below. There are extra string and not the filename.extension only:
ListViewItem: {sample.txt}

Try something like this, it is using the SubItems Text Property.
foreach (ListViewItem f in lstProjectFiles.Items)
{
Console.WriteLine(f.SubItems[0].Text);
Console.WriteLine(f.SubItems[1].Text);
}

You are only loading the file name into the list box, not the FileInfo.
How about cheating a little and storing the FileInfo in the Tag property?
DirectoryInfo d = new DirectoryInfo(path);
foreach (FileInfo f in d.GetFiles("*.txt", SearchOption.AllDirectories))
{
lstProjectFiles.Items.Add(f.Name).SubItems.Add(f.DirectoryName.ToString()).Tag = f; // Store FileInfo in Tag property
}
...
foreach(ListViewItem f in lstView1.Items)
{
Console.Writeline(((FileInfo)f.SubItems[0].Tag).FullName);
}
Then you can access anything in the FileInfo object later on. Of course you may want to refactor & validate, but this is the gist of one approach you could take.

Related

Adding File and Directory to Array

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

How to rename multiple files after specific character in C#?

I am trying to rename multiple files in C# after specific character.
In my folder I have these files:
Application.xml.4589.done
Compatible.xml.8790.done
I want to rename these files like below:
Application.xml
Compatible.xml
Basically after .xml I am looking to remove everything.
Here is the code I am trying:
public static void Main(string[] args)
{
DirectoryInfo d = new DirectoryInfo(#"C:\Test\");
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
var extension = f.FullName.Substring(f.FullName.LastIndexOf('.'), f.FullName.Length - 20);
// Need help here
}
}
Can anybody help me with that?
Thanks
You can Split string by . and Take the first two elements from the split array and Join as a string. You will get the desire file name with an extension.
//I showed you minimal example to solve your problem, update your code accordingly.
var infos = new List<string>(){"Compatible.xml.8790.done", "Compatible.xml.8790.done"};
foreach (var f in infos)
{
var newFileName = string.Join(".", f.Split('.').Take(2));
Console.WriteLine(newFileName);
}
Try Online

Removing elements from list or not getting them in at all

I have list of filenames.
I need to exclude files with keyword in their name.
I have tried:
List<string> fileList = Directory.GetFiles(path).ToList();
foreach (string file in fileList)
{
if (file.Contains("KEYWORD"))
{
fileList.Remove(file);
}
}
Error I'm getting: The collection has been modified. The enumeration operation may not be started.
But it doesn't work. Do you know why or do you have any better solution?
Thanks.
Try This
List<string> fileList = new List<string>();
fileList.Add("ioerhg");
fileList.Add("ioerhg");
fileList.Add("KEYWORD");
List<string> fileListNew = fileList.Where(x => !x.Contains("KEYWORD")).ToList();

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

Categories

Resources