c# openFileDialog1.InitialDirectory from string - c#

Am pretty new to C# and i need some help on a project i make.
I making an application we need. The application is to search our DB2 for the case number given on textbox by user. This is working fine i retrieve all data i need just fine. Now i want to click a button and open file dialog and user can select one of the files that exists in a folder on our win server under the folder that exists and named with the case number given in text box. So the initial directory should be dynamically changed according to the value in the textbox.
On my first attempt i declared the case number on a
string public String Gazm = "155465";
then i called initial directory
openFileDialog1.InitialDirectory = $#"\\apollo\zm\{Gazm}";
and worked fine. Dialogue opened on \\apollo\zm\155465\ and i could choose the files in the folder. I was was happy and i thought that that was easy and that i now have only to change the value of Gazm variable to the one given by user and i will do that easy with:
Gazm = textBox2.Text;
.So i did all happy and when i clicked the button the dialogue opened in the \\apollo\zm\ and not at the \\apollo\zm\Gazm\ where Gazm = textbox.text.
I thought there is something wrong with the string construction so what i tried next is that i made a String foldername = $#"\\apollo\zm\"; and public string fld = ""; . then i edit in button_click where the case number from user is captured the string fld = foldername + azm; and i send this result to be displayed in a textbox to check if the result is the desired.
The result in the textbox was the desired path to the case's number folder but the openfiledialogue will still open on the \\apollo\zm\ where then path in the textbox was the \\apollo\zm\155465\ where 155465 was the case number i typed in the textbox.
As i told you am new in C# and i dont know if what am doing is possible.
Please be kind with noob ;)
i will paste my code now which is only the code that reffers to the openfile dialogue. I made a new solution just for that part so i can do my tests on test solution rather than my main project.
Thank you for any help .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
namespace AutoZhm
{
public partial class Form1 : Form
{
String Gazm = "";
String filename = "";
String foldername = $#"\\apollo\zm\";
public string fld = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
String Gazm = textBox1.Text;
string fld = foldername + azm;
textBox97.Text = fld;
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button4_Click_1(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = fld;
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox97.Text = openFileDialog1.FileName;
filename = textBox97.Text;
}
}
}
}

You have the fld variables defined twice, once in your class and once within your button1_Click method. I suspect that this is causing you trouble.
The fld variable within the button1_Click is defined as a local variable. Meaning that it only exists within that method. The fld variable defined in your class is not updated by this method as a result, in fact in the code you've shown it well never change from an empty string.
You can easily fix this by removing the type declaration (string fld = [..] to fld = [..]) within the button1_Click method. That will cause the code to use the class defined variable (which the button4_Click_1 can also access).
Now, as you want an adjustment of the input in your TextBox to determine the initial directory, you'll need to set openFileDialog1.InitialDirectory to the current value textBox97.Text.

Related

How to use label1 in more Forms?

private void rectangleButton3_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Excel Files only | *.xlsx; *.xls; *.csv;";
ofd.Title = "Choose the file";
if (ofd.ShowDialog() == DialogResult.OK)
label1.Text = ofd.FileName;
}
}
Hi, im trying to use label1 as my path to export .csv file into my project: https://ibb.co/wNbnqbg
and then in my second form im trying to import: https://ibb.co/mRG0q5S
but the problem is this code: https://ibb.co/Gv3fSPv dont know that label1 is.
Im trying to create main page where user choose with which .csv file will be working. After rectangleButton3_click you save that path into label1 and then in second form i want use this path /label1 to import data into datagridview.
You can't use label1 in a different forms because it's a private field of the form so you can't share value through this field. Also Label is a visual component and not intended for data storage.
To share the value between the two forms, you can create a property in the second form that takes the value from first form. You can set the property in the first form after Excel file has been selected.
public class SecondForm : Form
{
private string _filePath;
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
...
}
When you creating a new form you can set the value from label1 or other place. For example if you open the second form immediately after choosing file you can use next code:
private void rectangleButton3_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Excel Files only | *.xlsx; *.xls; *.csv;";
ofd.Title = "Choose the file";
if (ofd.ShowDialog() == DialogResult.OK)
{
SecondForm secondForm = new SecondForm();
secondForm.FilePath = ofd.FileName;
secondForm.Show();
}
}
}
Finally you can read FilePath in the second form because it's a part of your form and the value is already written from the first form.
If you need to access the value between many forms there are two ways to solve it.
"Good" and architecturally correct solution is to pass this value from form to form and to have a property for file path in each form. It's a right way because you will continue to have a loosely coupled architecture and be able to easily modify the code. For example the middle form may start to get the file path in a different way or the composition of the forms itself may change.
"Bad" and hacky solution is a global state with static properties which you can read and write in any place:
public static class ApplicationState
{
private static string _filePath;
public static string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
}
So you can write ApplicationState.FilePath = ofd.FileName or var filePath = ApplicationState.FilePath; in any place of your code. But the problem is that this violates the encapsulation principle, making it difficult to test and modify the code when developing the project because you will have a single value within the entire application.
You probably want to access it from other form or class.
First you have to declare the label as public or anything visible to other files;
The class calling it have to know the Form1 unit, you may need to add it to the uses clause, but I am not sure;
Then you call it by the complete name, for example Form1.label1.Text.

Using textbox to gather user's destination path for exporting a CSV in C# Windows application?

I'm looking for an option that allows a user to input their destination folder (Usually copy/Paste) into a text box on a Windows Application, and append the file's name with a specific name. However, I'm stuck as to how to accomplish this.
//Exporting to CSV.
string folderPath = MessageBox.Show(textBox1_TextChanged);
File.WriteAllText(folderPath + "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv", csv);
So it can look like: C:/DIR_9132017.csv, or Documents/DIR_9132017.csv, depending on what the user inputs into the textbox. I have nothing in my textbox code section at the moment, if that also gives a clearer picture about the situation.
Any help will be greatly appreciated. Thank you!
You can either use FolderBrowserDialog or can just copy/paste the path and create the directory.
Using FolderBrowserDialog
Step1 : Create Browse button (so that the user can choose the directory)
Step2 : Create Export button (Place the code to write the file here)
private void browseButton_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
var folderPath = folderBrowserDialog1.SelectedPath;
textBox1.Text = folderPath;
}
}
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
Using Copy/Paste
Step1 : Create Export button (User copy pastes the path. System create the directory and writes the file)
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
You would use a FolderBrowserDialog for that. After adding it to your form, you can use it like this:
public void ChooseFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath;
}
}
Source: https://msdn.microsoft.com/en-us/library/aa984305(v=vs.71).aspx
You haven't specified whether it's WinForms or WPF, so I'm using WPF, but is should be the same in WinForms.
To select the folder, you could use FolderBrowseDialog as follows. This code should be placed inside a button or some other similar control's Click event.
if (folderBrowse.ShowDialog() == DialogResult.OK)
{
txtPath.Text = folderBrowse.SelectedPath;
}
txtPath being a TextBox your selected path displayed in. You can substitute it with a simple string variable if you don't want to use a TextBox.
And if you want the user to be able to drag-drop a folder into a TextBox, you can create a TextBox control, and in it's PreviewDragOver and Drop events, you can do the following.
private void txtPath_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
private void txtPath_Drop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Length != 0)
txtPath.Text = files[0];
}
Using both above in combination user has the ability to either select the folder he/she wants by clicking a button, drag-and-drop a folder into the TextBox, or copy-paste the folder path into the TextBox.

Insert chosen directory as a string into another method c#

I will spare you for a big background story to the program I'm creating here.
image
As the picture shows:
How do i get the directory result from the lowest method into the one above as a path string?
One way to do the job is by having a global variable like this:
string dir = ""; //Default
private void SelectDir_Click(object sender, EventArgs e)
{
//Open dialog and in dialog ok set dir
dir=dialog.Path;
}
private void UserValue_Click(object sender, EventArgs e)
{
var path=dir+"\\fileName.txt";
}
I was to lazy to type a code like yours but you'll get it :)
First, declare the variable to store your string.
private string userSelectedPath = "";
Create the FolderBrowserDialog:
xmodialog = new FolderBrowserDialog();
Check the result and retrieve the path selected by the user:
var result = xmodialog.ShowDialog();
if (result == DialogResult.OK)
{
userSelectedPath = xmodialog.SelectedPath;
}
Finally, you can use the stored path however you like:
File.WriteAllText(..., "A6_DRV_EDI=" + userSelectedPath);
It is up to you to enforce that the user first selects the path and only then uses it.

Get File Name from a Path in Listbox Item

I want to reduce the length of the path and display only the file name.
For example, suppose the path is c:\\program files\...\123.jpg I want to display only 123.jpg.
Here is the code I have been working with thus far. Can anyone suggest modifications?
private void button1_Click(object sender, EventArgs e)
{
panel3.Controls.Clear();
var ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.Cancel)
return;
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(s);
}
}
There is a class named Path in System.IO namespace.
Between its numerous static methods you could find
Path.GetFilename(string);
Using it in your Add loop you could set only the filenames
listBox1.Items.Add(Path.GetFileName(s));
However, I suggest to save the folder name somewhere, because if you need to process these files you need it. And, guess what, Path has a method also to extract a path from a full filename
if(filenames.Length > 0)
string workingPath = Path.GetDirectoryName(filenames[0]);
EDIT
From your comments below it seems that you call this button_click more than one time and every time you select a different folder. In this case, stripping the path part from the selected filenames leaves your listbox filled with files that you can't retrieve because you don't know the path part (stripped away). If you need to retrieve the files selected to execute some kind of process, then you need to store somewhere the full path of these files and be able to retrive them.
You can achieve this result storing the files selected in a List<string> instance.
Declare at the global level a variable to store these full filenames
(Add using System.Collection.Generic;)
List<string> selectedFiles = new List<string>();
Now inside the button click add the full filename to the List<string> and the stripped file to the ListBox items, in the same order
private void button1_Click(object sender, EventArgs e)
{
panel3.Controls.Clear();
var ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.Cancel)
return;
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileName(s));
selectedFiles.Add(s);
}
}
Now, if you want to retrieve the full path for the selected file in the listbox you could use
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(listBox1.SelectedIndex >= 0)
{
string fullFileName = selectedFiles[listBox1.SelectedIndex];
.... process the filename ....
}
}
Use Path.GetFileName() to return the name
see http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx

C# Windows fourms VS2012 - If statement not executing

I'm trying to make a simple program to either copy, move or sync (update and replace) files. I have a combobox where you select Copy, Move or Sync and so far I've only written a statement for when "Copy" is selected, and it calls a function that contains the process and sends in 2 args which is the source and destination for the files.
During debug it wasn't doing anything when I clicked the start button, so I ran through the code step by step selected "Copy" from the combobox entered the source and destination and pressed start and as it was highlighting each line, the IF statement for copy got highlighted but then carried on to the next ELSE IF and completely ignored the instructions under the "Copy" IF statement. Could you help me debug this problem please? I've checked for spelling errors and typos but I can't seem to find any, I don't understand why it's not executing it.
Thanks, my code is below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace File_Operator
{
public partial class FileOperatorV1 : Form
{
public FileOperatorV1()
{
InitializeComponent();
}
//Browse for source directory
private void sBrowse_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox1.
textBox1.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
//Browse for destination directory
private void dBrowse_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox2.
textBox2.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
//Start button
private void button1_Click(object sender, EventArgs e)
{
//If comboBox1 is equal to "Copy" do this
if (comboBox1.SelectedText == "Copy")
{
//Set var "s" to the contents of textBox1
string s = textBox1.Text;
//Set var "d" to the contents of textBox2
string d = textBox2.Text;
//Run function copyDirectory with var "d" and "s" as the args
copyDirectory(s,d);
}
//If comboBox1 is equal to "Move" do this
else if (comboBox1.SelectedText == "Move")
{
}
//If comboBox1 is equal to "Sync" do this
else if (comboBox1.SelectedText == "Sync")
{
}
}
//copyDirectory function
public static void copyDirectory(string Src, string Dst)
{
String[] Files;
if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar)
Dst += Path.DirectorySeparatorChar;
if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
Files = Directory.GetFileSystemEntries(Src);
foreach (string Element in Files)
{
// Sub directories
if (Directory.Exists(Element))
copyDirectory(Element, Dst + Path.GetFileName(Element));
// Files in directory
else
File.Copy(Element, Dst + Path.GetFileName(Element), true);
}
}
}
}
It reads this line
if (comboBox1.SelectedText == "Copy")
Ignores this
//Set var "s" to the contents of textBox1
string s = textBox1.Text;
//Set var "d" to the contents of textBox2
string d = textBox2.Text;
//Run function copyDirectory with var "d" and "s" as the args
copyDirectory(s,d);
And then carries on to here
else if (comboBox1.SelectedText == "Move")
I really don't understand why it's being ignored, and I'm very sure I've been selecting "Copy" in the combobox before any asks. Any help is appreciated. Many thanks.
I think instead of using SelectedText you should use Text. It gets or sets the text associated with this control.
if (comboBox1.Text == "Copy")
Here, problem with comboxBox1.SelectedText is that it gets the text that is selected in the editable portion of a ComboBox.
Check MSDN Reference.

Categories