Refactor browse file methods to one method - c#

I have several browse methods for parameters which only differ in which setting and which textbox is used. Can I create a lambda or generic method or something to have only one implementation in C#?
private void buttonBrowseSrcXML_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
try
{
fileDialog.InitialDirectory = Path.GetDirectoryName(Settings.Default.XML_Original_File);
}
catch (ArgumentException) { }
if (fileDialog.ShowDialog() == DialogResult.OK)
{
Settings.Default.XML_Original_File = fileDialog.FileName;
Settings.Default.Save();
textBoxSrcXML.Text = fileDialog.FileName;
}
}

yes, you can move this code into a common method and then pass the setting and textbox to this method and call in each of your methods like the one below.
BrowseFile("XML_Original_File", textBoxSrcXML);
you will need to use these values accordingly in this method.
the method's signature should be something like private void BrowseFile(string settingName, TextBox textbox)

The trick was the [] for settings indexing
private void BrowseForStringSettingsFile(System.Windows.Forms.TextBox textBox, string settingKey) {
OpenFileDialog fileDialog = new OpenFileDialog();
try {
fileDialog.InitialDirectory = Path.GetDirectoryName((string) Settings.Default[settingKey]);
} catch (ArgumentException) { }
if (fileDialog.ShowDialog() == DialogResult.OK) {
Settings.Default[settingKey] = fileDialog.FileName;
Settings.Default.Save();
textBox.Text = fileDialog.FileName;
}
}

Related

C# forms: how do I print out a CSV file which is selected using a different button

Goal: Direct print a CSV file which is selected from another button on my forms application
Problem: I don't know how to tell amy btnPrintFile_click method the FileName coming from another method in form1.cs
Any help would be appreciated, Im new to forms in c#
public void openCVSFile(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "CSV files (*.csv)|*.csv";
ofd.FilterIndex = 1;
if(ofd.ShowDialog() == DialogResult.OK)
{
txtAddressCount.Text = ("Address count: "+ ofd.FileName);
}
}
private void btnPrintFile_Click(object sender, EventArgs e)
{
try
{
streamToPrint = new StreamReader(ofd.FileName);
try
{
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler
(this.pd_PrintPage);
pd.Print();
}
finally
{
streamToPrint.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
For reference I'm using this article from Microsoft
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?redirectedfrom=MSDN&view=dotnet-plat-ext-6.0
public void openCVSFile(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
...
}
...
private void btnPrintFile_Click(object sender, EventArgs e)
{
try
{
streamToPrint = new StreamReader(ofd.FileName);
^^^
ofd was declared in the other method
Im new to forms in c#
This isn't about forms; you can never reach a variable declared inside one method, from another method.. the variable has to be passed from one method to the other, or it has to be declared at a scope that both methods can access.
Declare your OpenFileDialog under the class instead:
class YourForm: Form{
private OpenFileDialog ofd = new OpenFileDialog();
or drop it onto the form in the designer so it appears in the tray under the form view:
And rename it so it is called ofd by altering the (Name) line in the property grid:
Either of these ways make it accessible to all methods in the class. Doing it the visual way probably makes life easier in terms of setting other properties like the initial folder, file filter etc

How do i read already opened file in a another button click event directly .(i.e without open file dialogue in button click)

void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
var geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
}
How to read files in button1 click directly?
what you want is that your geometry object be accessible in additional scopes besides OpenPolyFile(). So you can simply make the geometry declaration accessible to both methods, declaring it, say, in the form code behind
// class scoped variables
[ThePolyFileType] (pick the right one here :) geometry = null;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
if (geometry != null)
{
//do your stuff
}
}
How do i read already opened file in a another button click event
directly .(i.e without open file dialogue in button click)
I'm not quite sure why you want to read it twice, but if that requirement says, make selected filename available globally and use it.
private string filename;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
filename = ofd.FileName
}
}
Now you have opened filename available in button_clcik you can use this file and read again.
private void button1_Click(object sender, EventArgs e)
{
// now you can read the file.
//File.ReadAllText(filename); //OR
TriangleNet.IO.FileReader.ReadPolyFile(file);
}

Choose file C# and get directory

I'm trying to open a file dialog box so the user can choose the location of an access database. Can someone explain how to add a file dialog when a button is clicked and also how to transform the user choice into a string that contains the file directory ( c:\abc\dfg\1234.txt)?
Thanks
As you did not state the technology you use (WPF or WinForms), I assume you use WinForms. In that case, use an OpenFileDialog in your code. After the dialog was closed, you can get the selected full file name using the FileName property.
There is the following example of how to use it on the documentation page I linked above, which I modified slightly as you want the file name, not the stream:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "Database files (*.mdb, *.accdb)|*.mdb;*.accdb" ;
openFileDialog1.FilterIndex = 0;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string selectedFileName = openFileDialog1.FileName;
//...
}
}
Based on your previous question I assume you are using WinForms.
You can use the OpenFileDialog Class for this purpose. See the code below which will run on your button Click event assuming your button id is button1:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Access files (*.accdb)|*.accdb|Old Access files (*.mdb)|*.mdb";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
var path = openFileDialog1.FileName;
}
}
More information.
Assuming that you actually have a form with button (button1)...
At the constructor hook into button1's click event
...
button1.Click += button1_Click;
...
Then define the handling function and use System.Windows.Forms.OpenFileDialog as you like.
void button1_Click(object sender, EventArgs e)
{
string oSelectedFile = "";
System.Windows.Forms.OpenFileDialog oDlg = new System.Windows.Forms.OpenFileDialog();
if (System.Windows.Forms.DialogResult.OK == oDlg.ShowDialog())
{
oSelectedFile = oDlg.FileName;
// Do whatever you want with oSelectedFile
}
}
It's actually fairly simple
namespace YourProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string path = "";
//Declare the File Dialog
OpenFileDialog ofd = new OpenFileDialog();
private void button1_click(object sender, EventArgs e)
{
if (odf.ShowDialog() == DialogResult.OK)
{
path = ofd.FileName;
}
}
}
}

Pass path from form on button click

I am using this code to generate the path of a selected file:
private void LoadNewFile()
{
OpenFileDialog ofd = new OpenFileDialog();
string _xmlPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
userSelectedFilePath = ofd.FileName;
}
}
private void tbFilePath_TextChanged(object sender, EventArgs e)
{
}
Before i used this code to pass the data:
private void btn_compare_Click(object sender, EventArgs e)
{
string x1 = System.IO.File.ReadAllText(#"C:\Users", Encoding.UTF8);
How do i modify it that instead of x1 that takes the path manually, i need it to be equal to xmlPath1 , so string x1 = xmlPath1
Just change _xmlPath1 to a field and you can access it from any method within your class.
Example:
public class MyClass
{
protected String _xmlPath1;
' insert your methods here
}
If your methods are not in the same class you have to widen the scope of _xmlPath1 even more.
EDIT: Changed VB.net syntax to C#
1 )If userSelectedFilePath is a private field you can use it in btn_compare_Click
2 )If it is a local variable ,make it a private field and then see 1
3)Make the the method return the file
private string LoadNewFile()
{
OpenFileDialog ofd = new OpenFileDialog();
string _xmlPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
return ofd.FileName;
else
return null;
}
and use it (you must add validation logic)
private void btn_compare_Click(object sender, EventArgs e)
{
string x1 = System.IO.File.ReadAllText(LoadNewFile(), Encoding.UTF8);
}
Option 3 is the best way so you can avoid the extra field and make btn_compare_Click independent from the rest of the code.
In that case you should also give it a better name like GetFileToRead()

Keep the last selected path using OpenFileDialog / C# / .Net

I want to keep the last path which is selected. This is the code:
private void testFileButton_Click(object sender, EventArgs e)
{
fd = new OpenFileDialog();
fd.FileName = testParameters.testFileFile;
fd.InitialDirectory = testParameters.testFileDir;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
if (fd.SafeFileName != null)
{
testParameters.testFileDir = Path.GetDirectoryName(fd.FileName);
testParameters.testFileFile = Path.GetFileName(fd.FileName);
testFileLabel.Text = fd.FileName;
}
}
catch (IOException)
{
MessageBox.Show("Error: Could not read file");
}
}
}
to be able to keep the last selected path, I tried to add RestorDirectory and index but I did not get any result:
private void testFileButton_Click(object sender, EventArgs e)
{
fd = new OpenFileDialog();
fd.FileName = testParameters.testFileFile;
fd.InitialDirectory = testParameters.testFileDir;
fd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
fd.FilterIndex = 2;
fd.RestoreDirectory = true;
if(...){
...
}
}
then I tried to use "else" instead:
private void testFileButton_Click(object sender, EventArgs e)
{
fd = new OpenFileDialog();
fd.FileName = testParameters.testFileFile;
fd.InitialDirectory = testParameters.testFileDir;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
if (fd.SafeFileName != null)
{
testParameters.testFileDir = Path.GetDirectoryName(fd.FileName);
testParameters.testFileFile = Path.GetFileName(fd.FileName);
testFileLabel.Text = fd.FileName;
}
}
}
catch (IOException)
{
MessageBox.Show("Error: Could not read file");
}
}
else
{
openFileDialog1.InitialDirectory = #"C:\";
}
}
but again without any result..
Does anyone have any idea?
Editing: Last attemp
private void testFileButton_Click(object sender, EventArgs e)
{
//http://stackoverflow.com/questions/7793158/obtaining-only-the-filename-when-using-openfiledialog-property-filename
OpenFileDialog fd = new OpenFileDialog();
fd.FileName = testParameters.testFileFile;
Environment.CurrentDirectory = #"C:\" ;
if (fd.ShowDialog() == DialogResult.OK )
{
try
{
if (fd.SafeFileName != null)
{
string ffileName = fd.FileName;
testParameters.testFileDir = Path.GetDirectoryName(ffileName);
testParameters.testFileFile = Path.GetFileName(ffileName);
testFileLabel.Text = ffileName;
}
}
catch (IOException)
{
MessageBox.Show("Error: Could not read file");
}
}
}
The documentation states:
true if the dialog box restores the current directory to its original value if
the user changed the directory while searching for files; otherwise, false.
Update: Changing my answer a little, since I think I may have misunderstood your intention:
If I'm not mistaken, your dialog will open to fd.InitialDirectory each time you open it, since that is per definition the default for a new instance of fd. I believe this might be your problem here: You are calling fd = new OpenFileDialog(); each time you are trying to open it.
If you change your code to use the same instance for fd each time (define it in an outer scope, and e.g. access a singleton instance via a Property?), it might remember it's previous directory itself - that is the default behavior (which you can override using the RestoreDirectory property).
Example of getting a singleton instance: This will only instantiate the dialog once, and return the same instance each time you call the property:
Private OpenFileDialog _fd;
private OpenFileDialog SingleFd {
get { return _fd ?? (_fd = new OpenFileDialog()); }
}
// Now in your method, use:
var singleInstance = SingleFd;
You are not using same variable for file dialog everywhere. Like in if block you are showing file dialog fd, but in else part you are using variable openFileDialog. I couldn't understand why you are doing this, or probably it is a typo. Use same variable at both place if you want to set initial directory to "C:\" if user cancels the dialog.
Instead of creating instance in every call, create an instance once and use it for subsequent calls.
Regarding directory restore, if we don't set initial directory, by default it restores the previous directory, even for the different instances.
OpenFileDialog initially uses the current directory which is a process-wide setting. You have overridden this behavior by setting the InitialDirectory. Just don't do that and it will work.
If you want to persist the last directory used across process restarts, capture Environment.CurrentDirectory and save it. Set it before opening the dialog.
Note, that the current directory is a process-wide setting so that different parts of the app can interfere. Also, all relative paths are interpreted relative to this directory (which is why relative path are usually a bug waiting).
string path = #"C:\";
OpenFileDialog fd = new OpenFileDialog();
fd.FileName = "SelectFolder";
fd.InitialDirectory =path;
fd.ValidateNames = false;
fd.CheckFileExists = false;
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
if (fd.SafeFileName != null)
{
string txt1 = System.IO.Path.GetFullPath(fd.FileName),
txt2 = txt1.Replace("SelectFolder", "").Trim();
testFileLabel.Text = txt2.Replace(path, "").Replace(#"\", ""); ;
}
}
catch (IOException)
{
MessageBox.Show("Error: Could not read file");
}
}
The Solution is to set the InitialDirectory path Blank
openFileDialog.InitialDirectory = ""
openFileDialog.RestoreDirectory = True

Categories