I am trying to add items from FileInfo into my RadListBox although I am not able to, I tried casting the file into a RadListBoxItem object, but I get the error that it can not convert a string to a radlistboxitem. Can someone shed a little light? thanks.
DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(fp));
lb_Files.Items.Clear();
foreach (FileInfo file in dir.GetFiles())
{
RadListBoxItem rlb = new RadListBoxItem();
rlb = (RadListBoxItem)file.ToString();
//radListBox
lb_Files.Items.Add(rlb.ToString());
}
Try this
DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(fp));
lb_Files.Items.Clear();
foreach (FileInfo file in dir.GetFiles())
{
lb_Files.Items.Add(new RadListBoxItem(file.ToString(), file.ToString()));
}
No you cannot cast a String object into a RadListBoxItem, you must create a RadListBoxItem using that string as your Value and Text properties:
So replace this:
RadListBoxItem rlb = new RadListBoxItem();
rlb = (RadListBoxItem)file.ToString();
//radListBox
lb_Files.Items.Add(rlb.ToString());
With this:
lb_Files.Items.Add(new RadListBoxItem
{
Value = file.ToString(),
Text = file.ToString()
});
Related
This question already has answers here:
Getting file names without extensions
(14 answers)
Closed 6 years ago.
I'm currently creating a note taking application. I'm trying to add items to a listbox without their file extensions, I have tried GetAllFilesWithoutExtensions, but no luck. I'm currently able to add them but can't seem to remove the extension. Any advice would be greatly appreciated...
DirectoryInfo dir = new DirectoryInfo("../Debug/");
FileInfo[] files = dir.GetFiles("*.txt");
foreach (FileInfo file in files)
{
listBox1.Items.Add(file);
}
You can use LINQ and System.IO.Path.GetFileNameWithoutExtension
var fileNamesWithoutExtension = files
.Select(fi => System.IO.Path.GetFileNameWithoutExtension(fi.Name));
foreach(string fn in fileNamesWithoutExtension)
{
// ...
}
You could use System.IO.Path.GetFileNameWithoutExtension(string)
See MSDN
Create a class to help you:
class FInfo
{
public FileInfo Info { get; set; }
public FInfo (FileInfo fi) { Info = fi; }
public override string ToString()
{
return Path.GetFileNameWithoutExtension(Info.FullName);
}
}
Now fill the ListBox with instances of that class:
DirectoryInfo dir = new DirectoryInfo(yourPath);
FileInfo[] files = dir.GetFiles(yourFilter);
foreach (FileInfo file in files) listBox1.Items.Add(new FInfo(file));
Now you can access the full FileInfo data:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FInfo fi = listBox1.SelectedItem as FInfo;
if (fi != null) Console.WriteLine(fi.Info.FullName); // do your thing here!
}
And the ListBox will use the ToString method to display only the file names without path or extension..
Im trying to load images from a folder and then inserting them into a tag.
For now i have this that i took from another question:
public string GetImage()
{
string imPath;
imPath = HttpContext.Current.Server.MapPath("~/Layout/Images/Banner");
DirectoryInfo directoryInfo = new DirectoryInfo(imPath);
FileInfo[] fileInfo = directoryInfo.GetFiles();
ArrayList arrayList = new ArrayList();
foreach (FileInfo fi in fileInfo)
arrayList.Add(fi.FullName);
return imPath;
}
But its not returning the images, only the folder path.
Just adding an answer so I can point out what everyone is confused about here.
What you've done here:
public string GetImage()
{
string imPath;
imPath = HttpContext.Current.Server.MapPath("~/Layout/Images/Banner");
DirectoryInfo directoryInfo = new DirectoryInfo(imPath);
FileInfo[] fileInfo = directoryInfo.GetFiles();
ArrayList arrayList = new ArrayList();
foreach (FileInfo fi in fileInfo)
arrayList.Add(fi.FullName);
return imPath;
}
Is equivalent to the following:
public string GetImage()
{
return HttpContext.Current.Server.MapPath("~/Layout/Images/Banner");
}
This is why everyone is a little confused.
Perhaps this is what you want (refactored a little bit)?
public ArrayList GetImage()
{
DirectoryInfo directoryInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Layout/Images/Banner"));
ArrayList arrayList = new ArrayList();
foreach (FileInfo fi in directoryInfo.GetFiles())
arrayList.Add(fi.FullName);
return arrayList;
}
It's because you return the image path.. You probably want the ArrayList you're making.
change:
return imPath;
to:
return arrayList;
and change:
public string GetImage()
to:
public ArrayList GetImage()
I also reccomend renaming that arraylist, and try to do a little more research before asking questions. If you understood what return is, you would've know what the problem is.
And as you can read in the comments of your question, you shouldn't be using ArrayList. I'm no expert on C# so that will have to be answered by someone else.
I have a list box and its populated by this method,
private void ToReadFromExcel_Load(object sender, EventArgs e)
{
string folderpath = #"\\gibson\users";
// Call the method to show available files
PopulateListBox(ExcelListBox, folderpath, "*.csv");
}
// To populate list box with csv files from given path
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file.Name);
}
}
String strItem;
foreach (Object selecteditem in ExcelListBox.SelectedItems)
{
strItem = selecteditem as String;
MessageBox.Show(strItem);
}
// read csv file information and insert into detail table
string filepath = #"\\gibson\users\CampManager.csv";
StreamReader sr = new StreamReader(filepath);
I hard coded the file path now, but I need to pass the filepath that was selected in the listbox. I have the file name in the variable stritem. If I want to pass the whole folder path how would I do that?
There is an ideal way. You should, instead of adding the FileInfo object's Name, should add the FileInfo object itself. So later you will be able to retrieve any piece of info related to that object, in your case say size, parent folder etc, and not just file name. Do it like this:
// To populate list box with csv files from given path
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file); //<-- note here
}
}
String strItem;
foreach (FileInfo selecteditem in ExcelListBox.SelectedItems)
{
StreamReader sr = new StreamReader(selecteditem.FullName);
//or whatever
}
One thing you should take care of here is to set the DisplayMember property of the ListBox like this:
ExcelListBox.DisplayMember = "Name";
What this does is to set the what property of the object in the listbox should be displayed. So here you choose FileInfo.Name which is what you want. This is how typically custom objects are added to ListBoxes in WinForms. You do not add just the string part of it typically. Akin to DisplayMember, there is also ValueMember property which is used to assign a value for each object, probably some id or so, but in your case nothing.
Few suggestions, 1) If you're using .NET 4, then use EnumerateFiles instead of GetFiles. The former is lazy and only yields a result when you start enumerating them (not beforehand), so it should be faster.
foreach (FileInfo file in dinfo.EnumerateFiles(FileType)) //<-- note here
{
lsb.Items.Add(file);
}
2) Use a using clause to dispose your stream reader properly, since that wont lock your file. It's always a good practice to make use of using. Its better on eyes than manual closing and disposing! Like this or so:
foreach (FileInfo selecteditem in ExcelListBox.SelectedItems)
{
using(StreamReader sr = new StreamReader(selecteditem.FullName))
{
//your code here
}
}
I'd like to load the multiple files (like Images, Documents, Pdfs) to the listview and along its properties will be displayed.
This was the code I am working with:
FileInfo FInfo;
DialogResult dr = this.openFD.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFD.FileNames)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem item = new ListViewItem(fileName);
item.Tag = file;
listView1.Items.Add(item);
}
}
Please help me.
Here is the way I do for Excel files. You just need to modify it a bit. I am hoping this helps.
private void loadMatchingResponsesReports()
{
listBox2.Items.Clear();
string[] list = getMatchingReports();
foreach (String S in list)
{
FileInfo fileResponse = new FileInfo(S);
string fileResponseNameOnly = fileResponse.Name;
listBox2.Items.Add(fileResponseNameOnly);
GC.Collect();
}
}
public string[] getMatchingReports()
{
string[] returnR = null;
try
{
returnR = Directory.GetFiles(textBox3.Text + #"\", "*.xls");
}
catch
{
MessageBox.Show("Can't get some files from directory " + textBox3.Text);
}
return returnR;
}
Instead of a simple string, you might want to use a custom object to store all properties you want associated with the ListViewItem.
item.Tag = file;
file should be of custom type, a Dictionary<string, string> maybe.
You need to use the FileInfo class. For each file you want to add, construct an instance. It as has all the properties you would want to add to an explorer like interface such as: CreationTime, Extension, Name etc. You get the size (in bytes) from the Length property.
You would add a ListViewSubItem for each attribute, corresponding to the column in your ListView.
How do I change the Read-only file attribute for each file in a folder using c#?
Thanks
foreach (string fileName in System.IO.Directory.GetFiles(path))
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
// or
fileInfo.IsReadOnly = true;
}
You can try this : iterate on each file and subdirectory :
public void Recurse(DirectoryInfo directory)
{
foreach (FileInfo fi in directory.GetFiles())
{
fi.IsReadOnly = false; // or true
}
foreach (DirectoryInfo subdir in directory.GetDirectories())
{
Recurse(subdir);
}
}
Use File.SetAttributes in a loop iterating over Directory.GetFiles
If you wanted to remove the readonly attributes using pattern matching (e.g. all files in the folder with a .txt extension) you could try something like this:
Directory.EnumerateFiles(path, "*.txt").ToList().ForEach(file => new FileInfo(file).Attributes = FileAttributes.Normal);