How to convert FileInfo to FileInfo[] on string[]? - c#

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
}

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

c# listview displaying problems

so i have a listview that displays the filename of the text file thats fine
the problem is foreach textfile i have so say a file is called 8133.txt it has a image file to so 8133.jpg
i want that to match in my listview to the correct textfile
DirectoryInfo di = new DirectoryInfo("C:\\OmGRhys Student System Files - 2019\\");
FileInfo[] files = di.GetFiles("*.txt");
foreach (FileInfo f in files)
{
foreach (string imageFileName in Directory.GetFiles(path, "*.jpg"))
{
listView1.Items.Add(new ListViewItem(new string[] { f.Name, imageFileName }));
}
}
so..
and to keep that pattern for everyfile in the directorys
all textfiles and image files are in the same directory
Try this:
DirectoryInfo di = new DirectoryInfo("C:\\OmGRhys Student System Files - 2019\\");
FileInfo[] files = di.GetFiles("*.txt");
foreach (FileInfo f in files)
{
string imgName = Path.GetFileNameWithoutExtension(f.FullName) + ".jpg";
string imgFile = Path.Combine(di.FullName, imgName);
if (File.Exists(imgFile))
listView1.Items.Add(new ListViewItem(new string[] { f.Name, imgFile }));
}

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

Put checkedlistbox items in an array

Adding the items in a checkedListBox:
DirectoryInfo dinfo = new DirectoryInfo(#"D:\\templates");
FileInfo[] Files = dinfo.GetFiles("*.xml");
foreach (FileInfo file in Files)
{
checkedListBox1.Items.Add(file.Name);
}
foreach (string i in checkedListBox1.CheckedItems)
{
string[] array1 = i;
for (int k = 0; k < array1.Length; k++)
{
XmlDocument xdoc1 = new XmlDocument();
xdoc1.Load(array1[k]);
string s1 = array1[k].ToUpper();
int n = s1.IndexOf(array1[k]);
name1 = array1[k].Substring(n);
}
When I'm putting it in an array, with (string[] array1 = i;)
it's an giving error:
Cannot implicitly convert type 'string' to 'string[]' "
any suggestions?
You can not do that. You will need to do something like this
string[] array1 = new string[] { i };
You are trying to assign string to string[]. Which is not allowed.
string[] array1 = new string[]{i};
DirectoryInfo dinfo = new DirectoryInfo(#"D:\\templates");
FileInfo[] Files = dinfo.GetFiles("*.xml");
Array.ForEach(Files, str => checkedListBox1.Items.Add(str.Name));
foreach (string i in checkedListBox1.CheckedItems)
{
XmlDocument xdoc1 = new XmlDocument();
xdoc1.Load(i);
name1 = i.Substring(i.ToUpper().IndexOf(i));
}

My List<> returns the exact number of files found BUT displays the same data through the entire loop

PROBLEM:
In my Program, when I try to loop the entire List of file found, I got exactly the 8 files on my List BUT displayed the same data value.
DEFINITION:
Class:
1.SearchFile.cs = has a method that accepts 2 parameters(PathToSearch and fileExtensionToSearch) then returns a List of "FileDetails" type.
public List<FileDetails> fileListFound = new List<FileDetails>();
public List<FileDetails> GetListFiles(string strPath, string strFileExtension)
{
DirectoryInfo dirInfo = new DirectoryInfo(strPath);
FileInfo[] files = dirInfo.GetFiles(strFileExtension, SearchOption.AllDirectories);
FileDetails fileDetails = new FileDetails();
foreach (FileInfo currentFile in files)
{
fileDetails.FileFullName = currentFile.FullName;
fileDetails.FileFullPath = strPath;
fileListFound.Add(fileDetails);
}
return fileListFound;
}
2.FileDetails.cs
class FileDetails
{
public string FileFullName { get; set; }
public string FileFullPath { get; set; }
public string FileType { get; set; }
}
My Main Program:
static void Main(string[] args)
{
string strPath = #"C:\Users\Public\Pictures\Sample Pictures";
FileCollection fileCollected = new FileCollection();
List<FileDetails> listOfFileFound = fileCollected.GetListFiles(strPath, "*.jpg");
foreach (FileDetails fileFound in listOfFileFound)
{
Console.WriteLine("Full Name: " + fileFound.FileFullName + ", Path:" + fileFound.FileFullPath);
}
Console.ReadLine();
}
NOTE: Im using Console application just to be clear with my Problem.
Sample Output: (8 files found)
...\Pictures**Tulips.jpg**
...\Pictures**Tulips.jpg**
...\Pictures**Tulips.jpg**
etc.. looped 8 times with the same output
NOTE: I can tell that the SearchFile.cs Class found the 8 different files then add it to my List and return it successfully by putting some breakpoints (Debug).
You are always modifying the same instance of fileDetails. You need to allocate a new one inside the loop at every iteration:
foreach (FileInfo currentFile in files)
{
FileDetails fileDetails = new FileDetails();
fileDetails.FileFullName = currentFile.FullName;
fileDetails.FileFullPath = strPath;
fileListFound.Add(fileDetails);
}
Since fileDetails is a reference that gets added to the list, modifying the same instance will cause all the values in the list to be the same.
cause you put one instance in all the LIST
Change this:
FileDetails fileDetails = new FileDetails();
foreach (FileInfo currentFile in files)
{
fileDetails.FileFullName = currentFile.FullName;
fileDetails.FileFullPath = strPath;
fileListFound.Add(fileDetails);
}
to this:
foreach (FileInfo currentFile in files)
{
FileDetails fileDetails = new FileDetails(); // IN THE LOOP
fileDetails.FileFullName = currentFile.FullName;
fileDetails.FileFullPath = strPath;
fileListFound.Add(fileDetails);
}
The fileDetails variable represents a class, which means it's a reference type, which means you're simply putting one identical item into the list eight times - that is, when you set the file details with lines such as,
fileDetails.FileFullName = currentFile.FullName;
You're just updating the class instance data, which will be reflected in each reference.
what you will need to do is create a new instance of FileDetails per file, as in:
foreach (FileInfo currentFile in files)
{
fileListFound.Add(
new FileDetails
{
FileFullName = currentFile.FullName,
FileFullPath = strPath
}
);
}
You should create new FileDetails object for every list item. Otherwise you overwrite the same item every loop.
Thats because your foreach loop contains bad code.
You need to re-declare fileDetails on each iteration - what happens is that
all of your fileListFound object contains ONE copy of the object fileDetails, and when you change
the last one - it changes the rest.
Here's the fixed code:
public List<FileDetails> fileListFound = new List<FileDetails>();
public List<FileDetails> GetListFiles(string strPath, string strFileExtension)
{
DirectoryInfo dirInfo = new DirectoryInfo(strPath);
FileInfo[] files = dirInfo.GetFiles(strFileExtension, SearchOption.AllDirectories);
foreach (FileInfo currentFile in files)
{
FileDetails fileDetails = new FileDetails();
fileDetails.FileFullName = currentFile.FullName;
fileDetails.FileFullPath = strPath;
fileListFound.Add(fileDetails);
}
return fileListFound;
}

Categories

Resources