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.
Related
I am making program, which copy files from directory to other directories in Windows Forms C#. But I tried save and load directory path to Preferences > Settings and its not working. Copying, deleting its already good, only this saving and loading doesnt work. I want do this: user can in textbox write path to source and target directory and save it. That when user want copy files, he dont need write path again and again because program save path in this preferences.
Form:
There are source path and target path for directory. Then "Save values" should save this paths as string. And "Save backup" copy files. Text_box1 is textbox next to "Source path" and text_box2 is "Target path"
Here is code:
namespace AutoSave
{
public partial class Form1 : Form
{
string sourcePath;
string targetPath;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
var dir = new DirectoryInfo(targetPath);
if (dir.Exists)
{
DeleteDirectory(targetPath);
CopyFiles();
}
else
{
CopyFiles();
}
}
private void CopyFiles()
{
try
{
System.IO.Directory.CreateDirectory(targetPath);
var dir1 = new DirectoryInfo(sourcePath);
foreach (FileInfo file in dir1.GetFiles())
{
string targetFilePath = Path.Combine(targetPath, file.Name);
file.CopyTo(targetFilePath);
}
label2.Text = "Save is successful";
}
catch
{
label2.Text = "Something is wrong";
}
}
public static void DeleteDirectory(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
//SAVE PATHS
private void button2_Click(object sender, EventArgs e)
{
sourcePath = textBox1.Text;
targetPath = textBox2.Text;
Properties.Settings.Default.SourcePath = targetPath;
Properties.Settings.Default.TargetPath = sourcePath;
Properties.Settings.Default.Save();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
Have I bad code or what I did bad please? Have you some tips? In advance I am sorry for my English i tried my best :D Thanks for help.
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);
}
So I have created a form that creates both a .txt file and a directory with the same name under the directory C:\Modules.
I have made it possible to select the .txt files from ModuleSelectorComboBox and now what I am having trouble getting to work is using the name of the file selected in ModuleSelectorComboBox to form part of the name of the directory in NoteSelectorComboBox.
public Default()
{
InitializeComponent();
System.IO.Directory.CreateDirectory(#"C:\Modules");
string[] files = Directory.GetFiles(#"C:\Modules");
foreach (string file in files)
ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
{
NewModule newmodule = new NewModule();
newmodule.Show();
}
private void ModuleSelectorComboBox_SelectedValueChanged(object sender, EventArgs e)
{
richTextBox1.Clear(); //Clears previous Modules Text
string ModulefileName = (string)ModuleSelectorComboBox.SelectedItem;
string filePath = Path.Combine(#"C:\Modules\", ModulefileName + ".txt");
if (File.Exists(filePath))
richTextBox1.AppendText(File.ReadAllText(filePath));
else
MessageBox.Show("There's been a problem. Please restart the program. \nError 1", "Error 1", //error 1 is file deleted while the program is running
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
private void button1_Click(object sender, EventArgs e)
{
ModuleSelectorComboBox.Items.Clear();
string[] files = Directory.GetFiles(#"C:\Modules");
foreach (string file in files)
ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
private void NoteSelectorComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string ModulefileName = (string)ModuleSelectorComboBox.SelectedItem;
string[] files = Directory.GetFiles(#"C:\Modules\" + ModulefileName); //THIS IS WHAT I HAVE TRIED BUT CANNOT GET TO WORK
foreach (string file in files)
NoteSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
}
So if 'Module 1' is selected in the ModuleSelectorComboBox the directory listing for NoteSelectorComboBox will be set to C:\Modules\Module 1 (ie. C:\Modules\<NAME OF SELECTED MODULE From ModuleSelectorComboBox> and so the files in that folder would be shown in the ComboBox.
I have created an OnClick(); event that has now solved this issue.
private void button2_Click(object sender, EventArgs e)
{
string fileName = (string)ModuleSelectorComboBox.SelectedItem;
NoteSelectorComboBox.Items.Clear();
string[] files = Directory.GetFiles(#"C:\Modules\" + (string)ModuleSelectorComboBox.SelectedItem);
foreach (string file in files)
NoteSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
From below given foreach loop I'm getting all the file names in a folder. I want to know how to put all the file names in text box. According to below code only the last file name appear in textbox.
private void btnGetFileNames_Click(object sender, EventArgs e)
{
DirectoryInfo dinf = new DirectoryInfo(tbxFileLocation.Text);
foreach (FileInfo Fi in dinf.GetFiles())
{
tbxFileList.Text=Fi.ToString();
}
}
Use a StringBuilder and append the filenames to it, Display finally
StringBuilder filenames = new StringBuilder();
foreach (FileInfo Fi in dinf.GetFiles())
{
filenames.Append(Fi.ToString());
filenames.Append(",");
}
tbxFileList.Text=filenames.ToString();
Try this :
private void btnGetFileNames_Click(object sender, EventArgs e)
{
DirectoryInfo dinf = new DirectoryInfo(tbxFileLocation.Text);
foreach (FileInfo Fi in dinf.GetFiles())
{
tbxFileList.Text+=Fi.ToString() + Environment.NewLine;
}
}
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));
}