C# SaveFileDialog doesn't create a file and won't close - c#

I'll start by noting that I'm a complete beginner to C# and I've been trying to "learn by doing."
The overall project is a media player that I'm creating and augmenting from a couple of YouTube videos I've been watching. I'm at a point where I'd like to understand the SaveFileDialog and how to save items from a ListBox into an xml file.
Before I can get there, however, I'm having trouble with just getting the SaveFileDialog to save anything at all and then close.
Here's the code I'm working with:
public Form1()
{
InitializeComponent();
}
private void btn_save_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "XML-File | *.xml";
saveFileDialog1.Title = "Save Playlist";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK) ;
}
Right now, when I click the "Save" button (btn_save), the Save dialog will open and it will default to an xml file, but no file will save after clicking Save, and then after clicking Save, the dialog just opens again and again until I select Cancel.
If I try to add
SaveFileDialog.Close();
I get an error saying "SaveFileDialog" does not contain a definition for 'Close', but I figure I've got to set something that tells the dialog to close after hitting Save.
What will help me most here is the "fix" for this and then some comments in the code that explain what's occurring on each line so that I perform more relevant searches and read further.
That said, any help with this would be appreciated. Please let me know if I need to include additional code in this example.

Here's have I would expect code that writes "hello world" to a text file to look like:
private void btn_save_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text file | *.txt";
saveFileDialog1.Title = "Save Playlist";
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
return;
File.WriteAllText(saveFileDialog1.FileName, "hello world");
}
You can tweak it for XML etc, but the key concepts are:
Show the dialog with ShowDialog() - your code will pause at that point while the dialog is open and resume when it closes
Inspect the result and if it's not OK (i.e. the user clicked Cancel), return without doing anything
Otherwise, do something (like writing a file)

You actually need to save the file with the information obtained from the SaveFileDialog component.
Maybe this could be helpful to you:
public Form1()
{
InitializeComponent();
}
private void btn_save_Click(object sender, EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "XML-File | *.xml";
saveFileDialog1.Title = "Save Playlist";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
} //end if ShowDialog
} //end Click Button

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

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.

Open File Dialog box on Clicking Link Label

I've created a log in panel in which I've used Transparent group box(with user name text box and password text box), and used a wallpaper on background, now I've Used a link label on this log in panel by clicking on which the user can change the background wallpaper of the log in panel.
Means when user clicks on the link label (lnklblChangeBackGround) with text "Click Here to Change Background" open dialogue box will open and user can select the Wallpaper from here and then by clicking on OK or Select the wallpaper will be assigned to background of the log in panel
Can any one help me out that
how can i open a open dialogue box by clicking on the link label
how can i assign a select wallpaper to the background of my log in panel
Note: I'm Creating this using VS 2010 using C#. and it's a desktop App and i'm using winform here.
At first you have to add an Event (LinkClicked) to your Link Label.
Just place this code here to open a file dialog.
private String getPicture()
{
string myPic = string.Empty;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "jpg (*.jpg)|*.jpg|png (*.png)|*.png";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
myPic = openFileDialog1.FileName;
return myPic;
}
You can edit the filter to avoid the user choosing images, which is not supported in your opinion.
With this code below you can set the Background Image of your pictureBox
private void setBackground(String picture)
{
pictureBox1.Image = null;
pictureBox1.Image = Image.FromFile(picture);
}
And the final version would look like this
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
String myFile = getPicture();
setBackground(myFile);
}
if this is too much code or too complicated for you, then you can just put it all in one function like this
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string myPic = string.Empty;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "jpg (*.jpg)|*.jpg|png (*.png)|*.png";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
myPic = openFileDialog1.FileName;
pictureBox1.Image = null;
pictureBox1.Image = Image.FromFile(myPic);
}

how can I save a file in a diffrent format?

I have a quick question, how do you save a file in a different format like in "save as"
so far i got this
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
//this saves the file as a text or richtext.
saveFileDialog1.Filter = ("RichText*.rtf; )|*.rtf; |TextDocs *.txt;|*.txt");
saveFileDialog1.FilterIndex = 2;
//this gives the title of the savefiledialog.
saveFileDialog1.Title = "save file";
//this prompts the user if they want to overwrite an existing file.
saveFileDialog1.OverwritePrompt = true;
//gets the input made by the savefiledialog.
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//saves the file.
richTextBox1.SaveFile(saveFileDialog1.FileName,
//saves the text in the richbox
RichTextBoxStreamType.RichText);
I want to be able to save as ether a rtf or a txt format. thanks.
Use filename different name and pass it to SaveFile with the read content buffer from origianl file.

Categories