I've started to learn about System.IO in C# and I want to achieve something like this:
I have two buttons and one TextBox.
The first button event is supposed to use FolderBrowserDialog and let me choose a specific a folder.Then, to save its path in a variable.
The text box is supposed to get as a value the number of folders that I want to create in the choosen path.
The second button is going to create the number of folders(with different name each) written in the textbox at the first button specified path.
My buttons and textbox events so far:
...
int value;
String path;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(fbd.SelectedPath);
path = folderBrowserDialog1.SelectedPath;//store selected path to variable "path"
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
}
private void button2_Click(object sender, EventArgs e)
{
if (!Directory.Exists(path))//if selected path exists
{
for(int i=0;i<value;i++)//trying to go through as folders as I wrote in the TextBox
{
Directory.CreateDirectory(path + "something");//is something wrong here, I guess.
}
}
}
My questions so far:
what's wrong with my code ?
how can I create each time the for(){} executes a folder with different name ?
I would appreciate any help
int value;
string path = null;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(fbd.SelectedPath);
path = fbd.SelectedPath; //fbd not folderBrowserDialog1
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
}
private void button2_Click(object sender, EventArgs e)
{
if (path != null && Directory.Exists(path))
for(int i=0;i<value;i++)
Directory.CreateDirectory(Path.Combine(path,string.Format("SomeFolder{0}",i)));
}
Related
So I'm trying to figure out how to change a buttons text based on having the buttons name as a variable. I already know how to change a buttons text by hardcoding its name like Button1.Text = "hello";
But I want to be able to do something like storing Button1's name in a string called value and then use that string to modify the buttons text so i can use a method for several buttons instead of pasting a huge similar block of code in every buttons method, I just cant seem to figure out how. Any ideas would help.
private void Button3_Click(object sender, EventArgs e)
{
Button obj = sender as Button;
string buttonname = obj.Name;
boxfill(buttonname);
}
private void Button4_Click(object sender, EventArgs e)
{
Button obj = sender as Button;
string buttonname = obj.Name;
boxfill(buttonname);
}
private void Button5_Click(object sender, EventArgs e)
{
Button obj = sender as Button;
string buttonname = obj.Name;
boxfill(buttonname);
}
// this will send the buttons name to boxfill
private void boxfill(string value)
{
// will ideally change the button named with value's
// text to "x"
}
Now solved. Thanks for your answers!
This is my code right now:
//Listbox scripts is the name of my folder
private void Form1_Load(object sender, EventArgs e)
{
foreach (var file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + #"Listbox scripts"))
{
string file2 = file.Split('\\').Last();
listBox1.Items.Add(file2);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("SetText", new object[]
{
File.ReadAllText(string.Format("./Listbox scripts/{0}", listBox1.SelectedItem.ToString()))
});
}
I'm new to coding in C# and I have a textbox that has the names of text files in a directory and when I click on the text file in the listbox it's supposed to load the text from it into my textbox (named 'ScriptBox')
Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
string User = System.Environment.MachineName;
textBox1.Text = "{CONSOLE} Welcome to Linst, " + User + "!";
directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + #"Scripts");
files = directory.GetFiles("*.txt");
foreach (FileInfo file in files)
{
listBox1.Items.Add(file.Name);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedFile = files[listBox1.SelectedIndex];
ScriptBox.Text = File.ReadAllText(selectedFile.FullName); //these parts are the parts that dont work
}
Thanks in advance!
Add the below into your Form1.cs. What this is going to do is when a user clicks a listbox item, its going to call (raise an event) the "listBox1_MouseClick" method and set the text of the textbox to the text of the listbox item. I just quickly created an app and implemented the below and it works.
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
textBox1.Text = listBox1.Text;
}
And add the below to the Form1.Designer.cs where the rest of your list box properties are. The below is subscribing to an event, the listBox1_MouseClick method in Form1.cs, so when a user clicks on a listbox item, the listBox1_MouseClick method is going to run.
this.listBox1.MouseClick += new MouseEventHandler(this.listBox1_MouseClick);
I hope the above makes sense.
Your code is nice, and perfect but it just need a little validation check in list index selection
Try thing in your listbox_selectedIndexChanged
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex!=-1)
{
FileInfo selectedFile = files[listBox1.SelectedIndex];
ScriptBox.Text = File.ReadAllText(selectedFile.FullName);
}
}
I actually don't see a problem with your code, could it be a typo somewhere?
I did this and it worked for me:
private void Form1_Load(object sender, EventArgs e)
{
foreach (var file in System.IO.Directory.GetFiles(#"c:\"))
{
listBox1.Items.Add(file);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
textBox1.Text = System.IO.File.ReadAllText(listBox1.SelectedItem.ToString());
}
}
I am trying to make a program for the car retail firm I work at. When people deliver their cars, a guy has to take pictures of the damages with a Lenovo miix.
The program I've made so far is not smart enough.
It goes like, you write the numberplate in a box, then create a folder with the text from the box.
Then you start the camera, take a picture and save it, and manually have to find the folder and name the file.
Is there a way I can make it smarter with just 2 buttons, one to start the camera and another one to take the picture, and then it automatically saves it in a folder named as the numberplate, and files named 1,2,3,4 and so on.jpg ?
this is my code so far:
namespace Europcar_skade_camera
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
private void Form1_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach(FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 1;
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
cam.Start();
}
private void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bit = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = bit;
}
private void button3_Click(object sender, EventArgs e)
{
if (cam.IsRunning)
{
cam.Stop();
}
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = #"C:\tmp\";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image.Save(saveFileDialog1.FileName);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void nummerplade_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(#"c:\tmp\" + nummerplade.Text);
}
}
}
Something like this:
Instead of using a SaveFileDialog, you could just create the file path based on the number plate value like this:
var filePath = System.IO.Path.Combine(#"c:\tmp", nummerplade.Text, fileNumber + ".jpeg");
The fileNumber var is the number of files allready in the folder + 1.
var fileNumber = Directory.GetFiles(...).Length + 1
string numberPlate = "21323412";
string path = #"C:\tmp\";
Directory.CreateDirectory(path + numberPlate); //to create folder
string dirpath = path + numberPlate; //to get name of fodler we created
You also mentioned that you want incremental names, there are many ways of doing it, personally i'd prefer large hashed name of file like so:
//generate GUID and convert to string.
string filename = Guid.NewGuid().ToString();
//to save picturebox image in folder and use ImageFormat.Your desired format
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg);
But if you want to stick with incremental names:
// you get last name in the folder:
//it gets last filename in folder but with path
var lastFilePath = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
//we remove path from filename and convert it to int.
int lastIndex = Int32.Parse(Path.GetFileNameWithoutExtension(lastFilePath));
//then we increment it by 1
int newName = lastIndex + 1;
//and save it
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg); //to save picturebox image in folder
With GUID finally it should look something like this:
string numberPlate = "21323412";
string path = #"C:\tmp\";
private void button2_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(path + numberPlate); //to create folder
string dirpath = path + numberPlate; //to get name of fodler we created
string filename = Guid.NewGuid().ToString();
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg); //to save picturebox image in folder
}
I have code like this:
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string ext = Path.GetExtension(openFileDialog1.FileName);
if(string.Compare(ext, ".FDB") == 0)
{
string fileName = openFileDialog1.SafeFileName;
string fileDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
string databaseTxt = #"C:\Users\arist\AppData\Roaming\TDWork\";
string[] database = { fileDirectory + fileName };
if (Directory.Exists(databaseTxt))
{
System.IO.File.WriteAllLines(databaseTxt + "databases.txt", database);
}
else
{
DirectoryInfo di = Directory.CreateDirectory(databaseTxt);
System.IO.File.WriteAllLines(databaseTxt + "databases.txt", database);
}
}
else
{
MessageBox.Show("Fajl koji ste izabrali nije Firebird baza (.FDB)");
e.Cancel = true;
}
}
Now, i want to create more buttons that open same file dialog. Problem is that i want to pass openFileDialog directory to different textboxes. So logic is this:
If i open with button1, pass value to textbox1,
If i open with button2, pass value to textbox2,
if i open with button3, pass value to textbox3.
So i wanted to create int check (1, 2, 3) so when i press button1, it pass check = 1 to OpenDialog1_FileOk, so i just do switch there and do actions.
Problem is i do not know how to pass it to handler, and if that is possible. Also if there is any other solution, please write it.
First, you could use your openfiledialog just like this, without handling a whole new function for it:
if(openFileDialog1.ShowDialog() == DialogResult.OK){
//...code
}
Second, for your goal you'll have to be sure that the names of your controls are exactly ending on the digit you want (e.g. "button1" and "textbox1"). Then you can do it like this:
void Button1Click(object sender, EventArgs e)
{
//MessageBox.Show(bt.Name[bt.Name.Length - 1].ToString());
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(!Path.GetExtension(openFileDialog1.FileName).EndsWith(".FDB")) //checking if the extension is .FDB (as you've shown in your example)
{
MessageBox.Show("Fajl koji ste izabrali nije Firebird baza (.FDB)");
return; //return if it's not and no further code gets executed
}
string fileDirectory = Path.GetDirectoryName(openFileDialog1.FileName); //getting the directory
string nameOfMyButton = (sender as Button).Name; //you get the name of your button
int lastDigitOfMyName = Convert.ToInt16(Name[Name.Length - 1]); //returns the number of your button
TextBox neededTextboxToShowDirectory = this.Controls.Find("textbox" + lastDigitOfMyName, true).FirstOrDefault() as TextBox; //this will search for a control with the name "textbox1"
neededTextboxToShowDirectory.Text = fileDirectory; //you display the text
//... doing the rest of your stuff here
}
}
You could use a private field where you save temporarily the text of your TextBox and deploy it in the click event like this:
private int whichButton = 0;
private void button1_Click(object sender, EventArgs e)
{
whichButton = 1;
openFileDialog1.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
whichButton = 2;
openFileDialog1.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
whichButton = 3;
openFileDialog1.ShowDialog();
}
use then the whichButton to choose
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
switch (whichButton)
{
....
}
}
I have made a simple application in Visual studio using C# that basically browses a folder, and the path of folder comes in text box - 'HideFolderAddress'. When the button 'AddToListBtn' is clicked it checks if there is a presence of the same item and if not it adds the item to list.
But this Prevent duplication in list view does not seems working! Can some one help me?
private void BrowsHide_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
HideFolderAddress.Text = fd.SelectedPath;
HideFolderAddress.Tag = Path.GetFileName(fd.SelectedPath);
}
}
private void AddToListBtn_Click(object sender, EventArgs e)
{
ListViewItem itemList = new ListViewItem(HideFolderAddress.Tag.ToString());
if (!FolderList.Items.ContainsKey(HideFolderAddress.Tag.ToString()))
{
itemList.SubItems.Add(HideFolderAddress.Text);
FolderList.Items.Add(itemList);
}
}
use it this way , because there will be no key if it is not created via Add method of ListViewItemCollection.
private void AddToListBtn_Click(object sender, EventArgs e)
{
string itemTag = HideFolderAddress.Tag.ToString();
if (!FolderList.Items.ContainsKey(itemTag ))
{
ListViewItem itemList = FolderList.Items.Add(itemTag , itemTag , -1);
itemList.SubItems.Add(HideFolderAddress.Text);
}
}