I'm new to programming and I'm starting to create a simple notepad, with only 4 buttons (Open, Save, New and Font).
If I open or save I'm getting an error:
This is my code:
//Declare save as a new SaveFileDailog
SaveFileDialog save = new SaveFileDialog();
//Declare filename as a String equal to the SaveFileDialog's FileName
String filename = save.FileName;
//Declare filter as a String equal to our wanted SaveFileDialog Filter
String filter = "Text Files|*.txt|All Files|*.*";
//Set the SaveFileDialog's Filter to filter
save.Filter = filter;
//Set the title of the SaveFileDialog to Save
save.Title = "Save";
//Show the SaveFileDialog
if (save.ShowDialog(this) == DialogResult.OK)
{
//Write all of the text in txtBox to the specified file
System.IO.File.WriteAllText(filename, textBox1.Text);
}
else
{
//Return
return;
}//Declare save as a new SaveFileDailog
SaveFileDialog save = new SaveFileDialog();
//Declare filename as a String equal to the SaveFileDialog's FileName
String filename = save.FileName;
//Declare filter as a String equal to our wanted SaveFileDialog Filter
String filter = "Text Files|*.txt|All Files|*.*";
//Set the SaveFileDialog's Filter to filter
save.Filter = filter;
//Set the title of the SaveFileDialog to Save
save.Title = "Save";
//Show the SaveFileDialog
if (save.ShowDialog(this) == DialogResult.OK)
{
//Write all of the text in txtBox to the specified file
System.IO.File.WriteAllText(filename, textBox1.Text);
}
else
{
//Return
return;
}
Any idea? Thanks and regards
ooopss I forgot to write the error sorry about that:
Here is the error:
"Error: ArgumentException was unhandled.
Empty path name is not legal"
I get this if I open a text file. Then it highlighted this line code:
textBox1.Text=System.IO.File.ReadAllText(filename,System.Text.Encoding.Default);
And if I save nothing happens.
Thanks
I expect you should be reading the filename after the user has used the dialog:
System.IO.File.WriteAllText(save.FileName, textBox1.Text);
Also - SaveFileDialog is IDisposable, so you should be "using" it...
using (SaveFileDialog save = new SaveFileDialog())
{
// your code that involves "save"
}
Try moving the line
String filename = save.FileName;
inside the IF block.
You are assigning to filename before the SaveDialog's property is set by the user.
You need to understand that this line does not create a permanent link between your filename variable and the FileName property of the dialog.
You get the filename from a SaveFileDialog after you call ShowDialog. You are setting filename beforehand.
Well, it looks like you're saving with a blank filename - this changes during the call to .ShowDialog(), so it doesnt help that you've retrieved it beforehand.
You just need to pull out .FileName again after .ShowDialog.
//To declare private int docno
//To declare private string filename
//To declare private bool modified=false;
if (modify == true)
{
//this.Text = filename;
filename = saveFileDialog1.FileName;
sw = new StreamWriter(filename);
sw.Write(textBox1.Text);
sw.Close();
//modify = false;
}
else
{
saveFileDialog1.FileName = "Untitled" + docno.ToString() + ".txt";
dresult = saveFileDialog1.ShowDialog();
docno++;
}
Related
I have been just hard coding a save name/location, but now I need to ask the user for the save location and file name. I have this syntax, but how do I actually pass the selected location & input file name to my ToExcel() method to know the file name and save locaiton?
private void btnSave_Click(object sender, EventArgs e)
{
//Creating Save File Dialog
SaveFileDialog save = new SaveFileDialog();
//Showing the dialog
save.ShowDialog();
//Setting default directory
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
//Setting title
save.Title = "Select save location and input file name";
//filtering to only show .xml files in the directory
save.DefaultExt = "xml";
//Write Data To Excel
ToExcel();
}
private void ToExcel()
{
var file = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Test_" + DateTime.Now.ToString("M-dd-yyyy-HH.mm.ss") + ".xlsx"));
using (var package = new ExcelPackage(file))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("Test");
ws.Cells[1, 1].Value = "One";
ws.Cells["A1:C1"].Style.Font.Bold = true;
package.Save();
MessageBox.Show("Saved!");
}
}
Firstly ShowDialog should be the last line of your call, after you have configured it
then use the FileName Property to access the selected Filename
finally pass that to whatever you need to pass it to ie
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xml"; // surely should be xlsx??
//Showing the dialog
if(save.ShowDialog() == DialogResult.OK)
{
ToExcel(save.FileName);
}
}
private void ToExcel(string saveFile){...}
also if you want to get the Directorty of a FileInfo check the FileInfo.Directory property
I have an image displaying on my C# form. When the user clicks "Save Image" button it pops up a Visual Basic input box. I am trying to add functionality to my form which allows the user to save the image when they enter the name of the image through the visual basic input box.
First, I added this code,
private void save_image(object sender, EventArgs e)
{
String picname;
picname = Interaction.InputBox("Please enter a name for your Image");
pictureBit.Save("C:\\"+picname+".Png");
MessageBox.Show(picname +" saved in Documents folder");
}
However, when I run the program and click the save button it gives this exception: "An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll"
Then I added few changes to the code to make it look like this,
private void save_image(object sender, EventArgs e)
{
SaveFileDialog savefile = new SaveFileDialog();
String picname;
picname = Interaction.InputBox("Please enter a name for your Image");
savefile.FileName = picname + ".png";
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (Stream s = File.Open(savefile.FileName, FileMode.Create))
{
pictureBit.Save(s, ImageFormat.Png);
}
//pictureBit.Save("C:\\pic.Png");
MessageBox.Show(picname);
}
When I run this code, it doesn't give the exception anymore but it saves the image in my c#->bin->debug folder. I know this might not be the ideal way of doing it but how do I set it's path so it saves the image in the documents folder.
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
savefile.FileName = path + "\\" + picname + ".png";
Other working example with show dialog:
SaveFileDialog savefile = new SaveFileDialog();
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
savefile.InitialDirectory = path;
savefile.FileName = "picname";
savefile.Filter = "PNG images|*.png";
savefile.Title = "Save as...";
savefile.OverwritePrompt = true;
if (savefile.ShowDialog() == DialogResult.OK)
{
Stream s = File.Open(savefile.FileName, FileMode.Create);
pictureBit.Save(s,ImageFormat.Png);
s.Close();
}
Other save example:
if (savefile.ShowDialog() == DialogResult.OK)
{
pictureBit.Save(savefile.FileName,ImageFormat.Png);
}
you are not setting the path, see MSDN for more info.
I have openfiledialog that reading user image address with file info and load it in textbox
I want to have another button in order to open image address (that already saved in textbox)
how to code this button at wpf ? I know i should use process.start but no idea !
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
tbl_Moshtari tt = new tbl_Moshtari();
dlg.FileName = "pic-file-name"; // Default file name
dlg.DefaultExt = ".jpg"; // Default file extension
dlg.Filter = "JPEG(.jpeg)|*.jpeg | PNG(.png)|*.png | JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; // Filter files by extension
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
//// picbox.Source = new BitmapImage(new Uri(dlg.FileName, UriKind.Absolute));
//bitmapImage = new BitmapImage();
//bitmapImage.BeginInit();
//bitmapImage.StreamSource = System.IO.File.OpenRead(dlg.FileName);
//bitmapImage.EndInit();
////now, the Position of the StreamSource is not in the begin of the stream.
//picbox.Source = bitmapImage;
FileInfo fi = new FileInfo(dlg.FileName);
string filename = dlg.FileName;
txt_picaddress.Text = filename;
System.Windows.MessageBox.Show("Successfully done");
}
This second button i have
private void btn_go_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//FileInfo fi = new FileInfo(dlg.FileName);
string filename = dlg.FileName;
Process.Start(filename);
}
This isnt working for me .
Process.Start() should open up the image as long as filename is an absolute path to the file. With that being said, where in your btn_go_Click method are you actually opening up the dialog to get the file name? dlg.FileName returns an empty string if you don't show the dialog in which case Process.Start() fails.
If the file name needs to come from the previous dialog, you shouldn't create a new dialog; instead, change
Process.Start(filename)
to
Process.Start(txt_picaddress.Text)
Of course, you need to do some input verification to make sure the path is correct (unless the textbox is read-only).
Also, consider setting a breakpoint on string filename = dlg.FileName; to make sure it has the correct path to the file if it's still not working.
To open and highlight the file in Windows Explorer:
string filename = txt_picaddress.Text;
ProcessStartInfo pInfo =
new ProcessStartInfo("explorer.exe", string.Format("/Select, {0}", filename));
Process.Start(pInfo);
In your second code sample, you created a new instance of openFileDialog, you need instead to use the previous instance of the openFileDialog that is holding the correct image filename:
if you create the first openFileDialog in the window constructor you can do this:
private void btn_go_Click(object sender, RoutedEventArgs e)
{
string filename = this.dlg.FileName;
Process.Start(filename);
}
hope this helps, this is what i can say given the code you provided.
You don't need an OpenFileDialog in btn_go_Click if you want to use the path in your textbox:
private void btn_go_Click(object sender, RoutedEventArgs e)
{
string filename = txt_picaddress.Text;
Process.Start(filename);
}
I already could open the save file dialog, but when i run the program and tried to save it, it could, but the file is not there. WHy is that? Here is the code:
_saved = false;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "System File (*.pos) | *.pos";
saveFileDialog1.Title = "Save File As";
saveFileDialog1.ShowDialog();
if (_saved)
{
this.Text = "Database - " + saveFileDialog1.FileName + "";
_filename = saveFileDialog1.FileName;
}
else
{
this.Text = this.Text;
}
Thank you, I appreciate your help.
The FileSaveDialog only gives you the UI to choose the file, once the file was choosen by the user you will get the FileName and is now your responsibility to do whatever is necesary with the FileName, such as storing your data and save it.
You should implement the save action by yourself, here is an example.
if(sf.ShowDialog() == DialogResult.OK)
{
using(var fs = new FileStream(sf.FileName,FileMode.Create))
{
// get bytes from text you want to save
byte [] data =new UTF8Encoding().GetBytes(text);
fs.Write(data,0,data.Length);
fs.Flush();
}
}
sf is saveFileDialog1
I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later.
Can anybody tell me how to obtain the file path from the save dialog box to use it later?
Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 1;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Console.WriteLine(saveFileDialog1.FileName);//Do what you want here
}
Addressing the textbox...
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = saveFileDialog.FileName;
}
private void mnuFileSave_Click(object sender, EventArgs e)
{
dlgFileSave.Filter = "RTF Files|*.rtf|"+"Text files (*.txt)|*.txt|All files (*.*)|*.*";
dlgFileSave.FilterIndex = 1;
if (dlgFileSave.ShowDialog() == System.Windows.Forms.DialogResult.OK && dlgFileSave.FileName.Length > 0)
{
foreach (string strFile in dlgFileSave.FileNames)
{
SingleDocument document = new SingleDocument();
document.rtbNotice.SaveFile(strFile, RichTextBoxStreamType.RichText);
document.MdiParent = this;
document.Show();
}
}
}
Try below code.
saveFileDialog1.ShowDialog();
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);