So, I set up a file browser, fully working.
But now I want to take the end location where you went and put that location into a TextBox. Which can still be typed in by the user for if they want to manually type the file location.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException) { }
}
Console.WriteLine(size);
Console.WriteLine(result);
}
You can get the full path
textBox1.Text = file;
and the last folder name
string lastFolderName = Path.GetFileName(Path.GetDirectoryName(file));
textBox1.Text = lastFolderName;
in your code you can use like below, if you want to use the location from another scope then make file variable global
string file = "";
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
textBox1.Text = file; // for full location
textBox2.Text = Path.GetFileName(Path.GetDirectoryName(file)); // for last folder name
}
catch (IOException)
{
}
}
}
and then
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = file;
}
Related
I am trying to output the file address of an item selected in a combobox. But i keep getting the Directory address of the project and not the item itself. Please help. Here is my Code:
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (availableSoftDropBox.SelectedItem.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
txtFlashFile.Text = openFileDialog1.FileName;
}
else
{
string fileName;
fileName = Path.GetFullPath((string)availableSoftDropBox.SelectedItem);
string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\" + (fileName);
txtFlashFile.Text = fullPath;
I'm not quite sure what you want to achieve, but using FileInfo instead of Path.GetFullPath might help.
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
const string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\";
string selection = (string)availableSoftDropBox.SelectedItem;
var fileInfo = new FileInfo(fullPath + selection);
string text = fileInfo.FullName;
if (selection.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
text = openFileDialog1.FileName;
}
}
txtFlashFile.Text = text;
}
I am having a problem with a with a code that I used for my C# application. When I click on the browse button and select the file dialogue box opens twice.
private void txt_location_TextChanged(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
folderPath = folderBrowserDialog1.SelectedPath;
}
}
private void Button21_Click(object sender, EventArgs e)
{
using(var fbd = new FolderBrowserDialog()) {
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) {
selectedPath = fbd.SelectedPath;
txt_location.Text = selectedPath;
}
}
}
private void bunifuThinButton21_Click_1(object sender, EventArgs e)
{
System.IO.StreamWriter file;
bool isvalid = ValidateInputs();
try {
file = new System.IO.StreamWriter(selectedPath + # "\dred.txt");
catch (Exception ex) {
MessageBox.Show("Please, Select valid Path..");
return;
}
try {
if (isvalid) {
WriteLines(file);
}
}
catch (Exception ex2) {
MessageBox.Show(ex2.Message);
}
finally {
file.Close();
}
}
}
Obviously, it is only meant to open once to enable me to read the selected file. This works, but only once I have selected the file twice.
Thanks in advance for your help.
You have FolderBrowserDialog being instantiated and shown on two different events:
txt_location_TextChanged
and
Button21_Click
You're having two popups because each one is firing once separately.
You should probably remove the event txt_location_TextChanged entirely unless you need it for another thing that isn't popping the FolderBrowserDialog again.
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 a question about the opfiledialog function within c#. When i dont select a file with openfiledialog it put's a text automaticly in my textbox. That text will be "filedialog1". What can i do to fix this.
using System;
using System.Windows.Forms;
using System.IO;
namespace Flashloader
{
public partial class NewApplication : Form
{
private toepassinginifile _toepassinginifile;
private controllerinifile _controllerinifile;
//private controllerinifile _controlIniFile;
public NewApplication(toepassinginifile iniFile)
{
_controllerinifile = new controllerinifile();
_toepassinginifile = iniFile;
InitializeComponent();
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
public bool Run()
{
var result = ShowDialog();
return result == System.Windows.Forms.DialogResult.OK;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
}
private void button3_Click(object sender, EventArgs e)
{
Toepassing toepassing = new Toepassing();
toepassing.Name = nameBox.Text;
toepassing.Controller = (Flashloader.Controller)controllerComboBox.SelectedItem;
toepassing.TabTip = descBox.Text;
toepassing.Lastfile = openFileDialog1.FileName;
fileBox.Text = openFileDialog1.FileName;
if (nameBox.Text == "")
MessageBox.Show("You haven't assigned a Name");
else if (controllerComboBox.Text == "")
MessageBox.Show("You haven't assigned a Controller");
else if (descBox.Text == "")
MessageBox.Show("You haven't assigned a Desciption");
else if (fileBox.Text == "")
MessageBox.Show("You haven't assigned a Applicationfile");
_toepassinginifile.ToePassingen.Add(toepassing);
_toepassinginifile.Save(toepassing);
MessageBox.Show("Save Succesfull");
DialogResult = DialogResult.OK;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
var newcontroller = new Newcontroller(_controllerinifile);
newcontroller.ShowDialog();
controllerComboBox.DataSource = null;
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
}
}
Thanks all for the help
private void button3_Click(object sender, EventArgs e)
{
toepassing.Lastfile = openFileDialog1.FileName;// Dont do this
fileBox.Text = openFileDialog1.FileName; //or this
Its unclear to me why you are holding onto an Open file dialog I would personally do the following
using(OpenFileDialog ofd = new OpenFileDialog())
{
if(ofd.ShowDialog() == DialogResult.OK)
{
classStringVariable = ofd.FileName;
fileBox.Text = ofd.FileName;
}
}
Then in button 3
toepassing.LastFile = classStringVariable ;
fileBox.Text = classStringVariable ;
When you use the Form Designer to add an OpenFileDialog control on you form, the designer assigns at the property FileName the value openFileDialog1.
I suppose you have set something as the initial value for the property FileName. Then in button_click3 you have no mean to check for the DialogResult and thus you get inconditionally this default back.
Fix it removing this default from the designer FileName property
Just add openFileDialog1.FileName= ""; before you show the dialog.
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != "")
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
In your button3_Click event you're checking for an empty string file name anyways, so they would get the correct error message and they wouldn't have some weird arbitrary default name show up when they open the dialog.
If I set path = "C:\\MSREAD.txt"; and Click on SaveAs Menu Item ,it saves Filetext,But If I dont give the String path and save it from saveFD.FileName it doesnt work.Please help me with this issue.
Thanks a lot
public void SaveToFile()
{
String SavedFile = "";
saveFD.InitialDirectory = #"C:";
saveFD.Title = "Save a Text File";
saveFD.FileName = "";
RichTextBox richTextBox1 = new RichTextBox();
saveFD.Filter = "Text Files|*.txt|All Files|*.*";
try
{
if (saveFD.ShowDialog() != DialogResult.Cancel)
{
SavedFile = saveFD.FileName;
path = SavedFile.ToString();
//path = "C:\\MSREAD.txt";
MessageBox.Show(path);
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveToFile();
}
public void SaveMyTextBoxContents(string path)
{
if (listBoxItems.SelectedIndex == -1)
{
if (rdBtnSlow.Checked && rdBtnNo.Checked)
{
using (StreamWriter outputFile = new StreamWriter(path))
{
foreach (string item in listBoxItems.Items)
{
saveAllText = slowNo + " " + item;
outputFile.WriteLine(saveAllText);
}
}
}
}
}
Here is your problem:
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);
You first save the richTextBox text to file, but then override the same file with SaveMyTextBoxContents, However the file is empty because of SaveMyTextBoxContents method will only save something if some conditions are true "not selected item and both check boxes are checked", and the listBoxItems.Items.Count > 0 which apparently not the case