I tried complete my program, with this code:
private void btnBuscar_Click(object sender, RoutedEventArgs e)
{
FileInfo f = null;
OpenFileDialog dlg;
dlg = new OpenFileDialog();
dlg.Filter = "Document Files (*.doc;*pdf)|*.doc;*pdf";
dlg.InitialDirectory = Environment.SpecialFolder.UserProfile.ToString();
dlg.Title = "Seleccione su archivo de cotizaciĆ³n.";
//Open the Pop-Up Window to select the file
bool? result = dlg.ShowDialog();
if (result == true)
{
f = new FileInfo(dlg.FileName,);
using (Stream s = dlg.OpenFile())
{
TextReader reader = new StreamReader(s);
string st = reader.ReadToEnd();
txtPath.Text = dlg.FileName;
}
File.Copy(dlg.FileName,#"C:\Formatos\m1");
}
}
The problem is when select the file with OpenFileDialog the program Crash automatically. I need copy the files only, and save the path of the copy file in the DB.
Thank you for you help!
Change bool? result = dlg.ShowDialog(); to if (dlg.ShowDialog() == DialogResult.OK)
Also, remove the extra comma from f = new FileInfo(dlg.FileName,);
Related
I am trying to save some selected file in a folder(images) inside my application
I am able to get the file using following code:
private void button1_Click(object sender, EventArgs e)
{
string imagelocation = "";
OpenFileDialog dialog = new OpenFileDialog();
if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
textBox2.Text = dialog.FileName;
}
}
For saving the file I got in textBox2, I tried following code. But with following code I have to also select the path where I want to save the file.
What If I want to (set my path permanently to 'images' folder as shown in pic) for saving?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog f = new SaveFileDialog();
if(f.ShowDialog() == DialogResult.OK)
{
using(Stream s = File.Open(f.FileName, FileMode.CreateNew))
using(StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox2.Text);
}
}
}
2 Approaches to Solve this problem
First Approach: (Browser the File and click Save, to automatically save the selected file to Image Directory)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
using (Stream s = File.Open(imageDir+"\\"+Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
Second Approach: (Browser the File and Save Opens SaveDialog with Directory as Image Directory and File name as Previously selected File)
private void button2_Click(object sender, System.EventArgs e)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
var imageDir = Path.Combine(assemblyParentPath, "Image");
if (!Directory.Exists(imageDir))
Directory.CreateDirectory(imageDir);
SaveFileDialog f = new SaveFileDialog();
f.InitialDirectory = imageDir;
f.FileName = textBox1.Text;
if (f.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(imageDir + "\\" + Path.GetFileName(textBox1.Text), FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.Write(textBox1.Text);
}
}
}```
Does this code work for you?
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Select Picture";
dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
dlg.Filter = "Common Picture Files|*.gif;*.png;*.bmp;|All Files|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.FileName;
}
}
At the moment I have three buttons on a form, each opens a different form (form2 with a textbox to display the text from the textfile, form3 with a picturebox to display the image)
What I am trying to do is put the two together for my last button so the user can filter which type to open (TXT Files or Image files). I am not sure how I can put the two together and get them to work.
The code I used to just open text files:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = #"C:\";
ofd.Filter = "TXT Files(*.txt;)|*.txt;";
if(ofd.ShowDialog() == DialogResult.OK)
{
using(StreamReader rdText = new StreamReader(ofd.FileName))
{
string info = File.ReadAllText(ofd.FileName);
TextDocumentForm newTextDocument = new TextDocumentForm();
newTextDocument.TextFileName = info;
newTextDocument.Show();
}
}
}
What I use to open my image files
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofdi = new OpenFileDialog();
ofdi.InitialDirectory = #"C:\";
ofdi.Filter = "Image Files(*.jpg;*.jpeg;*.bmp)|*.jpg;*.jpeg;.bmp;";
if (ofdi.ShowDialog() == DialogResult.OK)
{
Image image = Image.FromFile(ofdi.FileName);
ImgDoc newImageDoc = new ImgDocumentForm();
newImageDoc.ImageShow = image;
newImageDoc.Show();
}
}
Any help is appreciated as I am trying to develop my understanding of how OpenFileDialog still works.
Combining filters:
var openFile = new OpenFileDialog
{
InitialDirectory = #"C:\",
Filter = "TXT Files(*.txt;)|*.txt;|Image Files(*.jpg;*.jpeg;*.bmp)|*.jpg;*.jpeg;.bmp;"
};
Then use Path.GetExtension() to see which route you should take:
if (openFile.ShowDialog() == true)
{
var ext = System.IO.Path.GetExtension(openFile.FileName);
if (ext == ".txt")
{
// Open text file
}
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".bmp")
{
// Open image file
}
}
I am trying to save my rich text box content to a a file. However I am getting the error when I am trying to save a new file. Save as works as expected. Any suggestions. Thank you
System.ArgumentException: 'Empty path name is not legal.'
My code for the save and save as button are as follows:
OpenFileDialog file_open = new OpenFileDialog();
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
filename = file_open.FileName;
RichTextBoxStreamType stream_type;
// Checks the extension of the file to save
if (filename.Contains(".txt"))
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
DialogResult retval = saveDlg.ShowDialog();
if (retval == DialogResult.OK)
filename = saveDlg.FileName;
else
return;
RichTextBoxStreamType stream_type;
if (saveDlg.FilterIndex == 2)
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
MessageBox.Show("File Saved");
}
Now if you write the text and click on the save button, OpenFileDialog will appear. If you finish something in the same document and click on the save button again, you need to select the save location again. How to make that when saving the same file you do not need to create a new file each time, and just overwrite the current one? Sorry for my English.
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
}
else
{
}
}
It sure is, you just need to remember the last file path you saved and not display the dialog again the next time around; something like this should help:
void Main()
{
Save();
}
private string _filePath = "";
void Save()
{
var overwrite = false;
if (!string.IsNullOrEmpty(_filePath))
{
var res =
MessageBox.Show("Would you like to overwrite your last saved file?", "Overwrite?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly, false);
if (res == DialogResult.Cancel) return;
if (res == DialogResult.No) overwrite = false;
if (res == DialogResult.Yes) overwrite = true;
}
if (!overwrite)
{
var sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File|*.rtf";
var res = sfd.ShowDialog();
if (res != DialogResult.OK) return;
_filePath = sfd.FileName;
}
// do the richTextBox.SaveFile(_filePath) here.
}
In this example it:
CHECK IF FILE PATH ALREADY SET
IF NOT THEN
ASK USER IF THEY WANT TO OVERWRITE THE LAST FILE
IF CANCEL THEN DON'T SAVE
IF YES THEN SET OVERWRITE TO TRUE
IF NO THEN SET OVERWRITE TO FALSE
END IF
CHECK IF OVERWRITING
IF OVERWRITING THEN
SHOW SAVE FILE DIALOG
IF USER DIDN'T CLICK OK THEN DON'T SAVE
IF USER CLICKED OK, SET THE NEW FILE PATH TO USE
END IF
SAVE THE FILE USING THE NOW-REMEMBERED FILE PATH
Perhaps:
private void SaveButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = saveFileDialog1.FileName;
}
}
Example from: http://www.c-sharpcorner.com/uploadfile/mahesh/savefiledialog-in-C-Sharp/
Might help some?
private string filePath = string.Empty;
private void SaveButton_Click(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
byte[] buffer = Encoding.ASCII.GetBytes(richTextBox1.Text);
MemoryStream ms = new MemoryStream(buffer);
//write to file
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
}
else
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
sfd.OverwritePrompt = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
filePath = sfd.FileName;
}
}
}
you can use sfd.OverwritePrompt = false; property to avoid prompt messagebox if file already exists, is this what you are looking for ?
I want to show a dialog that will allow the user to select a shortcut (.lnk) file. My problem is that the dialog tries to get the file/URL the shortcut is pointing to rather then the .lnk file itself.
How can I make it allow .lnk files to be selected?
You can use the OpenFileDialog.DereferenceLinks property to influence that behaviour (see doc).
var dlg = new OpenFileDialog();
dlg.FileName = null;
dlg.DereferenceLinks = false;
if (dlg.ShowDialog() == DialogResult.OK) {
this.label1.Text = dlg.FileName;
}
or
var dlg = new OpenFileDialog();
dlg.FileName = null;
this.openFileDialog1.Filter = "Link (*.lnk)|*.lnk";
if (dlg.ShowDialog() == DialogResult.OK) {
this.label1.Text = dlg.FileName;
Both methods yield a .lnk file, however the first approach allows the selection of .lnk files or normal files, while the second only selects .lnk files.
The following code returned a .lnk filename for me
public static string PromptForOpenFilename (Control parent)
{
OpenFileDialog dlg = new OpenFileDialog ();
dlg.Filter = "Link (*.lnk)|*.lnk";
dlg.Multiselect = false;
dlg.FileName = null;
DialogResult res;
if (null != parent)
res = dlg.ShowDialog (parent);
else
res = dlg.ShowDialog ();
if (DialogResult.OK == res)
return dlg.FileName;
return null;
}