I have added all startup programs to a listbox.
How can I open the file when I select the item and click on a button?
Listbox code:
private void readfiles()
{
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
var files = Directory.GetFiles(startfolder).Where(name => !name.EndsWith(".ini"));
foreach (string file in files)
{
startupinfo.Items.Add(System.IO.Path.GetFileName(file));
}
}
I don't know what file type you're trying to open, but this is how you can get the selected item.
Dictionary<string, string> startupinfoDict = new Dictionary<string, string>();
private void readfiles()
{
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
var files = Directory.GetFiles(startfolder).Where(name => !name.EndsWith(".ini"));
foreach (string file in files)
{
startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
startupinfoDict.Add(Path.GetFileNameWithoutExtension(file), file);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
string s = listBox1.SelectedItem.ToString();
if (startupinfoDict.ContainsKey(s))
{
Process.Start(startupinfoDict[s]);
}
}
}
Get the currently selected list box item and assuming an application is coupled to the file('s extension use):
Process.Start(fileName);
You can get the selected item by using the SelectedValue property of the listbox.
You can open a file by using Process.Start.
You would initiate a new process declaring the path to the file to execute / open in your button click handler:
Process.Start(#" <path to file> ");
If the selected value in the list box is the file path then:
Process.Start(<name of list box>.SelectedValue);
EDIT:
Change your foreach loop as follows:
foreach (string file in files)
{
startupinfo.Items.Add(System.IO.Path.GetFullPath(file) + #"\" + System.IO.Path.GetFileName(file));
}
Related
Maybe this is an old question, but I canĀ“t find a solution fpr my project. Let me explain:
I have 3 Textboxes, who I can fill with values.
1 Button who save the values of the textboxes in a *.txt file. The Name of the file is the value of the first textboxes.
Then there is a ComboBox where I can select the txt files.
But I cant find the right code, when I selected a file, I want to see the 3 values(3 different lines) of the file into the Textboxes. Can someone help me, I will show you the Codes maybe its easier to understand.
the first code to save the values (tb1-3 = Textbox) in the txt file:
private void savebutton_click(object sender, RoutedEventArgs e)
{
string folder = #"C:\Users\...\...\...\Debug\";
string filename = tb1.Text + ", " + tb2.Text;
string writerfile = folder + filename;
using (StreamWriter writer = new StreamWriter(writerfile))
{
writer.WriteLine(this.tb1.Text);
writer.WriteLine(this.tb2.Text);
writer.WriteLine(this.tb3.Text);
}
}
The second code is to show the txt files in the combobox(combo1):
private void comboboxloaded(object sender, RoutedEventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\...\...\...\Debug");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
combo1.Items.Add(file);
}
}
And know... I need help...
private void comboboxvalueselect(object sender, SelectionChangedEventArgs e)
{
// Maybe?????
string fileName = combo1.SelectedItem.ToString();
string filePath = System.IO.Path.Combine(#"C:\Users\...\...\...\Debug" + fileName + "*.txt");
// and something with StreamReader??????
}
If I understand the question it could be as simple as using File.ReadAllLines
Opens a text file, reads all lines of the file into a string array,
and then closes the file.
private void comboboxvalueselect(object sender, SelectionChangedEventArgs e)
{
const string somePath = #"C:\Users\...\...\...\Debug";
var fileName = combo1.SelectedItem.ToString();
var filePath = Path.Combine(somePath , fileName);
// where you need those lines to go
someTextBox.Text = File.ReadAllLines(filePath);
}
I would like to make a file explorer with Windows Forms, i already have done a few things, but when i would like to use the DoubleClick event of my ListView I dont know how to code that file explorer needs to act differently when I make the doubleclick on a file or a folder.
My goal is:
Clicking on a file - Loads its text into a TextBox
Clicking on a directory - Opens it and loads it into the listview.
I know how to do 1. and 2. as well, I just don't know how can I make my DoubleClick function know what the selected item in ListView was 1. or 2.
I build my ListView like this:
private void miOpen_Click(object sender, EventArgs e)
{
InputDialog dlg = new InputDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
DirectoryInfo parentDI = new DirectoryInfo(dlg.Path);
listView1.Items.Clear();
try
{
foreach (DirectoryInfo df in parentDI.GetDirectories())
{
ListViewItem lvi = new ListViewItem(new string[] {
df.Name, df.Parent.ToString(),
df.CreationTime.ToShortDateString(), df.FullName });
listView1.Items.Add(lvi);
}
foreach (FileInfo fi in parentDI.GetFiles())
{
ListViewItem lvi = new ListViewItem(new string[] {
fi.Name, fi.Length.ToString(),
fi.CreationTime.ToShortDateString(), fi.FullName } );
listView1.Items.Add(lvi);
}
}
catch { }
}
}
Add the DirectoryInfo or the FileInfo objects to the Tag property of the ListViewItem. I.e
...
var lvi = new ListViewItem(new string[] {
df.Name,
df.Parent.ToString(),
df.CreationTime.ToShortDateString(),
df.FullName
});
lvi.Tag = df;
listView1.Items.Add(lvi);
...
or for the file info:
lvi.Tag = fi;
Then, after having selected an item in the listview:
private void btnTest_Click(object sender, EventArgs e)
{
// Show the first item selected as an example.
if (listView1.SelectedItems.Count > 0) {
switch (listView1.SelectedItems[0].Tag) {
case DirectoryInfo di:
MessageBox.Show($"Directory = {di.Name}");
break;
case FileInfo fi:
MessageBox.Show($"File = {fi.Name}");
break;
default:
break;
}
}
}
Try this code:
FileAttributes fileAttributes = File.GetAttributes("C:\\file.txt");
if (fileAttributes.HasFlag(FileAttributes.Directory))
Console.WriteLine("This path is for directory");
else
Console.WriteLine("This path is for file");
Here i have a problem, which is how to list the contents(files) of a search folder in listbox. The issue is i have many folder, each folder have many files with format .txt. I need, if i type the folder name in textbox and click the button, in the listbox shows all the files inside the search folder. In below i add my code, but it not works. Please help me....
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string search = TextBox1.Text; // here type the folder name
if (search != "")
//DirectoryInfo d = new DirectoryInfo(#"\\192.123.1.18\Report\Result" + search);
{
string[] files = Directory.GetFiles(#"\\192.123.1.16\Report\Result\"+ search + "*" + "*.*");
foreach (string file in files)
{
//ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file)); // listed all files in the search folder
}
{
search = "";
}
}
else
{
Response.Write("<script>alert('Please Enter Search Keyword');</script>");
}
}
Try this:
string[] files = Directory.GetFiles(#"\\192.123.1.16\Report\Result\"+ search, "*.txt", SearchOption.AllDirectories);
private void ToonInhoud()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string[] filePaths = Directory.GetFiles(path, "*.txt");
foreach (string file in filePaths)
{
cboLanden.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
}
}
private void cboLanden_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
StreamReader oSR = new StreamReader(path);
String sLijn = oSR.ReadLine();
while (sLijn != null)
{
string shops = sLijn;
lstWinkels.Items.Add(shops);
sLijn = oSR.ReadLine();
}
oSR.Close();
}
I have loaded 3 TEXT files in the first combobox and when 1 TEXT file is selected, I'd like to show the CONTENT in the Listbox using streamreader! So When you select TEXT file 1, i'd like the content of TEXT file 1 in the listbox, when I select TEXT file 2, I'd like the content of TEXT file 2 in the listbox, and so on.
To add lines from selected files:
void cboLanden_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach(string fileName in e.AddedItems)
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
foreach(string line in File.ReadLines(path))
lstWinkels.Items.Add(line);
}
// handle RemovedItems
}
If you want to get whole content of selected file, use
string content = File.ReadAllText(path)
I can reach with foreach to directory but, because of working like stack, I only reach last picture in the directory. I have lot of image that starting 1.jpg until 100.
namespace deneme_readimg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
foreach (FileInfo file in dir.GetFiles())
textBox1.Text = file.Name;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
I am unsure what you are asking or what you are trying to achieve, but if you want to see all of the names, you could change the foreach loop into:
foreach (FileInfo file in dir.GetFiles())
textBox1.Text = textBox1.Text + " " + file.Name;
As suggested by #LarsKristensen I'm posting my comment as an answer.
I would use the AppendText method, unless your requirement is to add to the text box on every click I would first make a call to Clear.
namespace deneme_readimg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
// Clear the contents first
textBox1.Clear();
foreach (FileInfo file in dir.GetFiles())
{
// Append each item
textBox1.AppendText(file.Name);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Just collect all the data you need to output in StringBuilder;
when ready publish it:
DirectoryInfo dir = new DirectoryInfo("C:\\DENEME");
// Let's collect all the file names in a StringBuilder
// and only then assign them to the textBox.
StringBuilder Sb = new StringBuilder();
foreach (FileInfo file in dir.GetFiles()) {
if (Sb.Length > 0)
Sb.Append(" "); // <- or Sb.AppendLine(); if you want each file printed on a separate line
Sb.Append(file.Name);
}
// One assignment only; it prevents you from flood of "textBox1_TextChanged" calls
textBox1.Text = Sb.ToString();
for displaying just File name. Use a multiline textbox
StringBuilder sb = new StringBuilder();
foreach (FileInfo file in dir.GetFiles())
sb.Append(file.Name + Environment.NewLine);
textBox1.Text =sb.ToString().Trim();
if you want to show images then you need to use some datacontainer like ListBox or DataGridView and add row for each image.