SaveFileDialog problem (C#) (VS2008)
Posted
by typoknig
on Stack Overflow
See other posts from Stack Overflow
or by typoknig
Published on 2010-04-28T20:31:35Z
Indexed on
2010/04/28
20:37 UTC
Read the original article
Hit count: 324
savefiledialog
|c#
Hi all, I am having an issue with SaveFileDialog for some reason. All I want to do is extract data from a text box line by line and write it to a text file, then save that text file to the desktop. The first bit of code works fine (though it doesn't save to the desktop). The second bit of code is what I want to use, but when it creates the text file the text file is empty. What did I do wrong in my second bit of code?
This code works, but it does not save to the desktop and it isn't as nice as the second code.
//When the Save button is clicked the contents of the text box will be written to a text file.
private void saveButton_Click(object sender, EventArgs e)
{
int textBoxLines = textBox.Lines.Count();
if (File.Exists(saveFile))
{
result = MessageBox.Show("The file " + saveFile + " already exists.\r\nDo you want to replace it?", "File Already Exists!", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
TextWriter tw1 = new StreamWriter(saveFile);
for (int i = 0; i < textBoxLines; i++)
{
tw1.WriteLine(textBox.Lines.GetValue(i));
}
tw1.Close();
}
if (result == DialogResult.No)
{
MessageBox.Show("Please move or rename existing " + saveFile + "\r\nBefore attempting to save again.", "Message");
}
}
else
{
TextWriter tw2 = new StreamWriter(saveFile);
for (int i = 0; i < textBoxLines; i++)
{
tw2.WriteLine(textBox.Lines.GetValue(i));
}
tw2.Close();
}
}
This code does not work, but it is what I want to use.
//When the Save button is clicked the contents of the text box will be written to a text file.
private void saveButton_Click(object sender, EventArgs e)
{
int textBoxLines = textBox.Lines.Count();
Stream saveStream;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
saveDialog.RestoreDirectory = true;
saveDialog.FileName = (saveFile);
saveDialog.InitialDirectory = (Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
if (saveDialog.ShowDialog() == DialogResult.OK)
{
if ((saveStream = saveDialog.OpenFile()) != null)
{
StreamWriter tw = new StreamWriter(saveStream);
for (int i = 0; i < textBoxLines; i++)
{
tw.WriteLine(textBox.Lines.GetValue(i));
}
saveStream.Close();
}
}
}
© Stack Overflow or respective owner