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)
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'm trying to create a file, add all the listbox items to the file. SO I can later on open the file and show all the listbox items again.
My current code is not working, it wont create a file or save to a existing file.
Function to get the name of thefile created / path
private void mnuFileSaveAs_Click(object sender, EventArgs e)
{
string fileName = "";
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
if(fileName == String.Empty)
{
mnuFileSaveAs_Click(sender, e);
}
else
{
fileName = sfd.FileName;
writeToFile(fileName);
}
}
}
Function to write to file
private void writeToFile(string fileName)
{
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fileName);
foreach (var item in listBox.Items)
{
SaveFile.WriteLine(item.ToString());
}
}
Well you didn't specify the error, but my guess is that it isn't working because you didn't close the StreamWriter.
using (System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fileName))
{
foreach (var item in listBox.Items)
SaveFile.WriteLine(item.ToString());
}
Or you can just call SaveFile.Close() instead of using
Say I want listBox1 to contain a set of first names. And when someone clicks on one of those first names, it will display the last name in listBox2 and already selected.
I seem to not be able to have the second listbox have it already selected.
So if the first item in listBox1 is selected, the first item in listBox2 is selected. And so on.
How would such be possible?
Here is some code:
private void materialFlatButton3_Click_1(object sender, EventArgs e)
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "DLL Files|*.dll";
OpenFileDialog1.Title = "Select a Dll File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// put the selected result in the global variable
fullFileName = new List<String>(OpenFileDialog1.FileNames);
foreach (string s in OpenFileDialog1.FileNames)
{
listBox2.Items.Add(Path.GetFileName(s));
listBox4.Items.Add(s);
}
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string text = listBox2.GetItemText(listBox2.SelectedItem);
textBox3.Text = text;
}
In listbox4, it displays the full path. In listbox2, it displays just the name of the file.
How would I make it so when someone clicks on a file in listbox2, its corresponding path will be selected in listbox4?
Create you own type for storing and displaying the file names:
public class FileItem
{
public FileItem (string path) => FullPath = path;
public string FullPath { get; }
public override ToString() => Path.GetFileName(FullPath);
}
And add these items to the listbox. That way you can store the full path and display the file name at the same time.
Alternatively just keep a reference to the original Files array or copy its content to another array. Then get the full path from this array through the selected index instead of from a second listbox ony used to store things.
Create a class which represent full path and name for displaying.
Then use bind loaded data to the ListBox
public class MyPath
{
public string FullPath { get; private set; }
public string Name '
{
get { return Path.GetFileName(s) }
}
public MyPath(string path)
{
FullPath = path;
}
}
// Load and bind it to the ListBox
var data = OpenFileDialog1.FileNames
.Select(path => new MyPath(path))
.ToList();
// Name of the property which will be used for displaying text
listBox1.DisplayMember = "Name";
listBox1.DataSource = data;
private void ListBox1_SelectedValueChanged(object sender, EventArgs e)
{
var selectedPath = (MyPath)ListBox1.SelectedItem;
// Both name and full path can be accesses without second listbox
// selectedPath.FullPath
// selectedPath.Name
}
I have this in my designer:
On the right is the files in a listView1.
On the left is the directory main directory of this files treeView1.
I have this code in menu strip item clicked event :
void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
List<String> selected = new List<String>();
foreach (ListViewItem lvi in listView1.SelectedItems)
{
selected.Add(lvi.Text);
}
AllFiles = selected.ToArray();
Bgw.RunWorkerAsync();
}
}
The problem is that the file/s in AllFiles array are only the filenames for example: bootmgr or install.exe
But i need that in the All Files each file will have also it's full path for example:
c:\bootmgr or c:\install.exe or c:\test\test\example.txt
How can i add to AllFiles also the paths ?
I tried now:
void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Upload")
{
List<String> selected = new List<String>();
string dir = treeView1.SelectedNode.FullPath;
foreach (ListViewItem lvi in listView1.SelectedItems)
{
string g = Path.Combine(dir, lvi.Text);
selected.Add(g);
}
AllFiles = selected.ToArray();
Bgw.RunWorkerAsync();
}
}
And in form1:
private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
{
f = new FtpSettings();
f.Host = "ftP://ftp.newsxpressmedia.com";
f.Username = "...";
f.Password = "...";
files = TV_LV_Basic.ExplorerTree.AllFiles;
StringArrayUploadFiles(sender, e);
}
AllFiles contain the files and paths for example C:\test.txt
Then :
private void StringArrayUploadFiles(object sender, DoWorkEventArgs e)
{
try
{
foreach (string txf in files)
{
string fn = txf;
BackgroundWorker bw = sender as BackgroundWorker;
if (f.TargetFolder != "" && f.TargetFolder != null)
{
createDirectory(f.TargetFolder);
}
else
{
f.TargetFolder = Path.GetDirectoryName(txf);
//createDirectory(f.TargetFolder);
}
string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(fn));
Now in txf for example i have C:test.txt
Then in f.TargetFolder i have: C:
Then in UploadPath i have: ftp://ftp.newsxpressmedia.com/C:/eula.1031.txt
But instead C: i need it to look like: ftp://ftp.newsxpressmedia.com/C/eula.1031.txt
And there are sub directories for example then: ftp://ftp.newsxpressmedia.com/C/Sub/Dir/eula.1031.txt
In the menuStrip1_ItemClicked event when i select a file for example test.txt already in this event i did a mess.
FileInfo fi = new FileInfo("temp.txt");
Determine the full path of the file just created.
DirectoryInfo di = fi.Directory;
Figure out what other entries are in that directory.
FileSystemInfo[] fsi = di.GetFileSystemInfos();
to display directoryinfo fullname in console
Console.WriteLine("The directory '{0}' contains the following files and directories:", di.FullName);
Print the names of all the files and subdirectories of that directory.
foreach (FileSystemInfo info in fsi)
Console.WriteLine(info.Name);
Here
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));
}