c# Openfiledialog - c#

When I open a file using this code
if (ofd.ShowDialog() == DialogResult.OK)
text = File.ReadAllText(ofd.FileName, Encoding.Default);
A window appear and ask me to choose file (The File Name is blank as you can see on the image)
If I press second time the button Open to open a file the File Name show the path of the previous selected file (see on image) How I can clear this path every time he press Open button?

You are probably using the same instance of an OpenFileDialog each time you click the button, which means the previous file name is still stored in the FileName property. You should clear the FileName property before you display the dialog again:
ofd.FileName = String.Empty;
if (ofd.ShowDialog() == DialogResult.OK)
text = File.ReadAllText(ofd.FileName, Encoding.Default);

try this:
ofd.FileName = String.Empty;

You need to reset the filename.
openFileDialog1.FileName= "";
Or
openFileDialog1.FileName= String.Empty()

you can simply add this line before calling ShowDialog():
ofd.FileName = String.Empty;

To clear just the filename (and not the selected path), you can set the property FileName to string.Empty.

private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
label1.Text = sender.ToString();
}
What about this one.

Related

C# OpenFileDialog importing variable

Still new to C#, snipping some code around to write a simple application and learning while doing.
I have an xml file that needs to be ingested and set as a variable so I can have it just insert words from that text file into different text fields.
private void button1_Click(object sender, EventArgs e)
{
// Displays an OpenFileDialog so the user can select a datafeed.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Datafeed File|*.dfx5";
openFileDialog1.Title = "Select a dfx5";
// Show the Dialog.
// If the user clicked OK in the dialog and
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Assign the file as a variable.
}
}
How would I make that file a variable so that I can read from it?
Thank you in advanced. Google-ing didn't return anything helpful
How would I make that file a variable so that I can read from it?
Well, the file name that was selected is a property of the OpenFileDialog object:
string fileName;
// Show the Dialog.
// If the user clicked OK in the dialog and
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Assign the file as a variable.
fileName = openFileDialog1.FileName;
}
What you do with that file name at that point is up to you.
If you want to store the Filename in a variable, the other answers are what you are looking for.
To me it sounds like you need to actually read the content of the file.
If that's what you want, the following snippet (provided by Microsoft) should do:
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
// Read the stream to a string, and write the string to the console.
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
This way line will contain the XML data you need. How you proceed from there is up to you.
If the file is pure XML, then I'd be inclined to do something like this:
using System.Xml.Linq;
private XDocument _xmlPayload;
private void button1_Click(object sender, EventArgs e)
{
// Displays an OpenFileDialog so the user can select a datafeed.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Datafeed File|*.dfx5";
openFileDialog1.Title = "Select a dfx5";
// Show the Dialog.
// If the user clicked OK in the dialog and
var dialogResult = openFileDialog1.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//Get file path from dialog
var filePath = openFileDialog1.FileName;
//load xml
using(var stream = File.OpenRead(filePath))
{
_xmlPayload = XDocument.Load(stream);
}
}
}
Then it's up to you how you work with the XML.
openFileDialog1.FileName should have the returned filename from the dialog. if multiselect is enabled I think its openFileDialog1.FileNames

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.

C# OpenFileDialog opening twice

I am having a problem with a windows form coded in Visual Studio using C# as part of a web development course. When I click on the menu item ('Import') the file dialogue box opens twice.
The first dialogue seems incorrect as it does not have the filter or title applied. Then the second dialogue box which immediately opens afterward has the correct filter and title applied.
Obviously it is only meant to open once to enable me to read the selected file and add it to the Listbox. This works, but only once I have selected the file twice.
Thanks in advance for your help.
private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
openFileDialog1.Filter = "Text|*.txt";
openFileDialog1.Title = "Choose a file to import";
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
{
MessageBox.Show("Oh. No file selected!");
}
else
{
string usersFile = openFileDialog1.FileName;
string[] lines = File.ReadAllLines(usersFile);
foreach (string line in lines)
{
groceryList.Items.Add(line);
}
}
Start of your code you have
private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
this is unneccessary, the ShowDialog will show a dialog with the filters not correctly set up as your next lines have:
openFileDialog1.Filter = "Text|*.txt";
openFileDialog1.Title = "Choose a file to import";
Then you ShowDialog again.
Therefore, just remove the first
openFileDialog1.ShowDialog();
and you should be fine.

Saving files with name read from text box. C#

I have created some code that saves my work to a text file, I was just wondering is there some way so that when I click 'Save' I can read in the text from richTextBox1and set it as the default file name, still with the 'txt' default file extension.
e.g. When I click 'save' the folder dialog comes up and asks you to name your file, just as it would if you were using Word for example, I want that box to already have the text from my richTextBox1 in.
Thanks.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = "C:\\To-Do-List";
save.Filter = "Text Files (*.txt)|*.txt";
save.DefaultExt = ".txt";
DialogResult result = save.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamWriter SW = new StreamWriter(save.FileName))
{
SW.WriteLine(richTextBox1.Text);
SW.WriteLine(richTextBox2.Text);
SW.WriteLine(richTextBox3.Text);
SW.WriteLine(richTextBox4.Text);
SW.WriteLine(richTextBox5.Text);
SW.Close();
}
}
Just set the FileName property on your SaveFileDialog.
Add
save.FileName = String.Format("{0}.txt", richTextBox1.Text);
Before you call ShowDialog.

Save Image to particular folder from Openfiledialog?

I want to save images to my project folder from openfiledialog result . I don't get foler path to save . How do I get folder path ? How do I save that ? Please Help me.
FileDialog.FileName gives the full path to the file. And btw it is probably easier to use the SaveFileDialog because you want to save something, not open.
Hello thinzar,
private void button2_Click(object sender, EventArgs e)
{
Bitmap myBitmap = new Bitmap();
this.saveFileDialog1.FileName = Application.ExecutablePath;
if (this.saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
myBitmap.Save(this.saveFileDialog1.FileName);
}
}
Bye
The System.Windows.Forms.FolderBrowserDialog allows the user to select a folder. Maybe that would be a better option?
Something alone these lines
Bitmap myImage = new Bitmap();
// draw on the image
SaveFileDialog sfd = new SaveFileDialog ();
if(sfd.ShowDialog() == DialogResult.OK)
{
myImage.Save(sfd.FileName);
}
I guess you're opening a file elsewhere and then using the results to later save stuff into the directory you opened from?
DialogResult result = OpenFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string directoryName = Path.GetDirectoryName(OpenFileDialog1.FileName);
// directoryName now contains the path
}

Categories