C# comboBox, readall and working directory
What I have is a comboBox being populated from a code:
InitializeComponent();
DirectoryInfo dinfo = new Dir开发者_StackOverflow中文版ectoryInfo(@"K:\ases");
FileInfo[] Files = dinfo.GetFiles("*.ssi", SearchOption.AllDirectories);
foreach (FileInfo file in Files)
{
comboBox1.Items.Add(file.Name);
}
Then i'm trying to ReadAllText from that selected item.
string contents = File.ReadAllText(comboBox1.Text);
When executed, it tries to read the file from the locale path, and of course the file isnt there. I also can't set the working directory because the comoboBox is populated from a huge range of subdirectories. How do I get the working directory of the item selected in the combobox WITHOUT expossing the whole directory path to the user?
Any help always welcomed
I thought i saw a few answers with someone suggesting private and hiding things in a combox box, where those suggestions taken down. is there a way to keep the full file info in the combobox and only display the file name?
There are several different ways to accomplish this, but the absolute easiest would be to store the directory path in an instance variable (we'll call it directoryPath
) and use System.IO.Path.Combine()
to reconstruct the path:
(some code eliminated for brevity)
public class Form1 : Form
{
private string directoryPath;
public Form1()
{
InitializeComponent();
DirectoryInfo dinfo = new DirectoryInfo(@"K:\ases");
FileInfo[] Files = dinfo.GetFiles("*.ssi", SearchOption.AllDirectories);
foreach (FileInfo file in Files)
{
comboBox1.Items.Add(file.Name);
}
directoryPath = dinfo.FullName;
}
private void YourFunction()
{
string contents = File.ReadAllText(System.IO.Path.Combine(directoryPath, comboBox1.Text);
}
}
You could also try adding the FileInfo
to the ComboBox
rather than the file's name and use SelectedItem
rather than Text
:
InitializeComponent();
DirectoryInfo dinfo = new DirectoryInfo(@"K:\ases");
comboBox1.DataSource = dinfo.GetFiles("*.ssi", SearchOption.AllDirectories);
comboBox1.DisplayMember = "Name";
Then you can do this to retrieve the file:
FileInfo file = (FileInfo)comboBox1.SelectedItem;
string contents = File.ReadAllText(file.FullName);
Instead of:
comboBox1.Items.Add(file.Name);
do:
comboBox1.Items.Add(file.FullName);
This will get you the full path to the file in order to read it.
See FileInfo for more details and other properties to use.
I think the best way for you is to use special class for items:
class FileInfoItem {
public FileInfoItem(FileInfo info) {
Info = info;
}
public FileInfo Info { get; set; }
public override string ToString() {
return Info.Name;
}
}
To add items in the combo box use the following code:
comboBox1.Items.Add(new FileInfoItem(file));
ComboBox will display the ToString() value of the items and also you can get the original FileInfo in the following maner:
((FileInfoItem)comboBox1.SelectedItem).Info;
精彩评论