I am trying to write notepad, how do I know if user clicked 'Cancel'? My code doesn't work:
private void SaveAsItem_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = "untitled";
saveFileDialog1.Filter = "Text (*.txt)|*.txt";
saveFileDialog1.ShowDialog();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(saveFileDialog1.FileName);
SaveFile.WriteLine(richTextBox1.Text);
SaveFile.Close();
if (DialogResult == DialogResult.Cancel)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
else
{
issaved = true;
}
}
You're checking the DialogResult property for your main form, but it's the child form that you want to check. So...
var dr = saveFileDialog1.ShowDialog();
if( dr == DialogResult.OK )
{
using(var SaveFile = new StreamWriter(saveFileDialog1.FileName))
{
SaveFile.WriteLine(richTextBox1.Text);
issaved = true;
}
}
else // cancel (or something else)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
Also, you should wrap your StreamWriter in a using block as I have done above. Your code will fail to close the file if an exception occurs. A using block is syntactic sugar for a try/finally block which calls Dispose() (which in turn calls Close()) in the finally portion.
DialogResult res = saveFileDialog1.ShowDialog();
if (res == DialogResult.Cancel) {
// user cancelled
}
else {
// Write file to disk using the filename chosen by user
}
You are creating the file before checking the result of the dialog. Move the SaveFile variable bit into the "issaved = true" block.
[edit] And as the others said, check the Dialog result properly
Related
Hello im having trouble with file dialog
Standard code, but it's freezing while selecting large files (600MB+ xls file that i need to first reformat to xlsb, then stream data from, but that is not important here).
What i wanted to achieve is to hide dialog when Open button is clicked, so that i could display Loading Message.
Yet im not sure how can i achieve that. Can i somehow subscribe to Open button?
OpenFileDialog openFile = new OpenFileDialog() { DereferenceLinks = false };
openFile.Title = "Select Supplier List";
openFile.Filter = "Excel files (*.*xls*)|*.*xls*";
try
{
if (openFile.ShowDialog() == true)
{
/* Takes long time to go after selection */
ViewModel.ReportPath = openFile.FileName;
ViewModel.FileTrueName = Path.GetFileName(ViewModel.ReportPath);
}
}
catch
{
ViewModel.ReportPath = null;
ViewModel.FileTrueName = null;
}
Wrapping code with task, helped :)
Some changes happened during searching for answer, based on comments.
Task.Run(() =>
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "Select Supplier List";
openFile.Filter = "Excel Files(*.xls; *.xlsx; *.xlsb; *.xlsm)| *.xls; *.xlsx; *.xlsb; *.xlsm";
try
{
if (openFile.ShowDialog() == true)
{
ViewModel.ReportPath = openFile.FileName;
ViewModel.FileTrueName = Path.GetFileName(ViewModel.ReportPath);
}
}
catch
{
ViewModel.ReportPath = null;
ViewModel.FileTrueName = null;
}
});
My program is supposed to be able to allow the user to be able to select a flavor of icecreame and syrup using (comboboxes) and selecting the three check boxes if they want nuts, cherries or sprinkles. WHICH IS WORKING TO THE BEST OF MY KNOWLEGE
the Other part of the Program is supposed to allow the user to save there order and open it later using StreamReader/Writer (WHICH ISNT WORKING REALLY WELL I CANT GET IT TO WRITE DOWN WHAT IS SELECTED OUT OF BOTH COMBO BOXES AND CHECK BOXES DONT WRITE EITHER. SAMETHING WITH THE OPEN IT ONLY OPENS IF I CHANGE THE INDEX NUMBER AFTER THE EQUALS)
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
//THIS IS MY SAVE BUTTON USING STREAMWRITER
//flavorBox is the Name of the comboBox that holds 3 flavors of iceCream
//syrupBox is the name of the comboBox that holds 3 syrupFlavors inside the combobox
// my check boxes for the toppings are the IF else if else statments
{
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(
new FileStream(sfd.FileName,
FileMode.Create,
FileAccess.Write)
);
if (!String.IsNullOrEmpty(syrupBox.Text))
{
sw.WriteLine(flavorBox.SelectedItem);
}
else if (!String.IsNullOrEmpty(syrupBox.Text))
{
sw.WriteLine(flavorBox.SelectedItem);
}
else if (Nuts.Checked)
{
this.Tag = "checked";
sw.WriteLine(Nuts);
}
else if (Cherries.Checked)
{
this.Tag = "checked";
sw.WriteLine(Cherries);
}
else if(Sprinkles.Checked)
{
this.Tag = "checked";
sw.WriteLine(Sprinkles);
}
sw.Close();
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
//THIS IS MY OPEN METHOD WHERE IT IS SUPPOSED TO DISPLAY EVERYTHING THAT USE SAVED
{
OpenFileDialog ots = new OpenFileDialog();
if (ots.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(
new FileStream(ots.FileName,
FileMode.Open,
FileAccess.ReadWrite)
);
String items;
// I tried coping my if else if statements for the save streamREader thinking that would work it doesn't DUH. I'm out of IDEAS for this COULD USE SOME HELP WITH THIS
while (!sr.EndOfStream)
{
items = sr.ReadLine();
flavorBox.Items.Add(items);
syrupBox.Items.Add(items);
if (Nuts.Checked)
{
this.Tag = "checked";
sw.WriteLine(Nuts);
}
else if (Cherries.Checked)
{
this.Tag = "checked";
sw.WriteLine(Cherries);
}
else if (Sprinkles.Checked)
{
this.Tag = "checked";
}
}
flavorBox.SelectedIndex = 1;
syrupBox.SelectedIndex = 1;
sr.Close();
}
}
First things first: if I interpret your capslock correct then I'd advise you to calm down. It's never going to be easy to find errors if you're in a rage mode.
I guess a big part of your problem may be the following lines:
if (!String.IsNullOrEmpty(syrupBox.Text))
{
sw.WriteLine(flavorBox.SelectedItem);
}
else if (!String.IsNullOrEmpty(syrupBox.Text))
{
sw.WriteLine(flavorBox.SelectedItem);
}
You check two times for syrupBox.Text and always use flavorBox.SelectedItem. I think you got syrupBox and flavorBox mixed up.
My issue is that I keep seeing a recurring theme with trying to allow my Notepad clone to save a file. Whenever I try to save a file, regardless of the location on the hard disk, the UnauthorizedAccess Exception continues to be thrown. Below is my sample code for what I've done, and I have tried researching this since last night to no avail. Any help would be greatly appreciated.
//located at base class level
private const string fileFilter = "Text Files|*.txt|All Files|*.*";
private string currentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private void MenuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "*.txt";
sfd.Filter = fileFilter;
sfd.AddExtension = true;
sfd.InitialDirectory = currentPath;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
sfd.ShowDialog();
try
{
System.IO.File.WriteAllText(currentPath,TxtBox.Text,Encoding.UTF8);
}
catch (ArgumentException)
{
// Do nothing
}
catch(UnauthorizedAccessException)
{
MessageBox.Show("Access Denied");
}
}
Change the following lines.
...
if (sfd.ShowDialog() != true)
return;
try
{
using (var stream = sfd.OpenFile())
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(TxtBox.Text);
}
}
...
I hope it helps you.
You need to get the correct path context and file object from the dialog box once the user has hit 'ok'. Namely verify the user actually hit ok and then use the OpenFile property to see what their file selection is:
if (sfd.ShowDialog.HasValue && sfd.ShowDialog)
{
if (sfd.OpenFile() != null)
{
// convert your text to byte and .write()
sfd.OpenFile.Close();
}
}
Whenever I try to open a custom file to a textbox or something which will display code. it never works, I'm not sure what I am doing wrong.
I want my program to display what is inside the file when I open it, I have this below:
private void button1_Click(object sender, EventArgs e)
{
//Show Dialogue and get result
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "rbt files (*.rbt)|*.rbt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show("RBT7 file open");
}
}
}
It only displays the RBT7 in a messagebox which is not what I want, I want the file to open and display its information to some sort of textbox which displays code.
Please read the documentation for File.WriteAllText.
The first parameter:
path: The file to write to.
You're passing it "". That is not a path. Are you trying to write all the text from the file into CodeBox.Text or write all the text from CodeBox.Text into a file?
In your comment, you indicate the former. Try this:
string[] lines = System.IO.File.ReadAllLines(#"your file path");
foreach (string line in lines)
{
CodeBox.Text += line;
}
You haven't shown the code for CodeBox so I can't guarantee the results of this.
Try this:
Replace this code
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
with this
{
CodeBox.Text = File.ReadAllText(openFileDialog1.FileName);
}
When I click the button to open a file the OpenFileDialog box opens twice. The first box only opens the image files and the second box text files. If the user decides to close out the first box without choosing a file the second box pops up as well. I'm not sure what I am over looking on this issue. Any help would be appreciated. Thanks!
OpenFileDialog of = new OpenFileDialog();
of.Filter = "All Image Formats|*.jpg;*.png;*.bmp;*.gif;*.ico;*.txt|JPG Image|*.jpg|BMP image|*.bmp|PNG image|*.png|GIF Image|*.gif|Icon|*.ico|Text File|*.txt";
if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
image1.Source = new BitmapImage(new Uri(of.FileName));
// enable the buttons to function (previous page, next page, rotate left/right, zoom in/out)
button1.IsEnabled = false;
button2.IsEnabled = false;
button3.IsEnabled = false;
button4.IsEnabled = false;
button5.IsEnabled = true;
button6.IsEnabled = true;
button7.IsEnabled = true;
button8.IsEnabled = true;
}
catch (ArgumentException)
{
// Show messagebox when argument exception arises, when user tries to open corrupted file
System.Windows.Forms.MessageBox.Show("Invalid File");
}
}
else if(of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
using (StreamReader sr = new StreamReader(of.FileName))
{
textBox2.Text = sr.ReadToEnd();
button1.IsEnabled = true;
button2.IsEnabled = true;
button3.IsEnabled = true;
button4.IsEnabled = true;
button5.IsEnabled = true;
button6.IsEnabled = true;
button7.IsEnabled = true;
button8.IsEnabled = true;
}
}
catch (ArgumentException)
{
System.Windows.Forms.MessageBox.Show("Invalid File");
}
}
You're calling ShowDialog() twice:
if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//...
}
else if(of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
Just call it once, and save the results:
var dialogResult = of.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//...
}
// Note that the condition was the same!
else if(dialogResult != System.Windows.Forms.DialogResult.OK)
Edit:
If you want the second dialog to only show when the first is handled, you can do:
var dialogResult = of.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//...
// Do second case here - Setup new options
dialogResult = of.ShowDialog(); //Handle text file here
}
You are calling ShowDialog both in the if and else if condition. That method is responsible for showing the dialog and only has the nice side effect of also telling you what the user clicked.
Store the method's result in a variable and check that in your if..elseif conditions instead.