Create, write to and open a text file from SaveFileDialog - c#

I am displaying a SaveFileDialog and when OK is clicked I am creating new file, writing some default content to it and then attempting to Open it via the OpenFile() method of the SaveFileDialog. However, the moment I call OpenFile() the content of the file are deleted.
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML files (*.xml)|*.xml";
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// First Event Creates file and writes default content to it - works ok
NewFileCreated( this, new FileCreatedEventArgs() { Template = Template.BBMF, FilePath = saveFileDialog.FileName } );
// Second Event clears file content as soon as saveFileDialog.OpenFile() called
FileLoaded( this, new FileLoadedEventArgs() { FileStream = saveFileDialog.OpenFile() } );
}
Can someone explain why this happens and what I need to be doing to successfully Open the newly created file?

According to MSDN, SaveFileDialog.OpenFile()
Caution
For security purposes, this method creates a new file with the
selected name and opens it with read/write permissions. This can cause
unintentional loss of data if you select an existing file to save to.
To save data to an existing file while retaining existing data, use
the File class to open the file using the file name returned in the
FileName property.

Related

C# WPF Have User select file then use the functions within that file

I'm new to using C# and WPF so I apologize if my terminology is incorrect.
I want trying to make a program to automate small businesses workflows, the base application is the same for everyone, but how their order data is structured is going to be different.
So, my goal would be to build them a custom file that contains function on how to parse their order data, then have the user drag and drop that file into the application to which the application would use it.
I have a way for them to select the file and move it into the applications directory here:
private void SelectFile_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".cs";
dlg.Filter = "C# Files (*.cs)|*.cs";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filePath = dlg.FileName;
string relPath = AppDomain.CurrentDomain.BaseDirectory;
string destPath = System.IO.Path.Combine(relPath, dlg.SafeFileName);
Trace.WriteLine(destPath);
File.Move(filePath, destPath, true);
}
}
But now I run into an issue when I want to call from that file I get a error "CS0103" the file doesn't exist in the current context. So I am now unable to run the application
Is there a way around this error? so it will only run when the file exists and get rid of this error?
I have tried to check if the file exists before calling it, but the same error prevents me from running my app.
//call your order parser script
if (File.Exists("OrderParser.cs"))
{
OrderParser.OrderParser.Parser(item);
}

How Read File Path From a .dat file then open the program When Pressing The Launch Button?

I have a problem Where I cant make my program automatically read the given file path inside the .dat and be ready to launch the program when pressing launch file without opening openFileDialog and choosing the program every time.
the code im using here is for the user to enter the file path for the first time then create a file path .dat file and it works with now issues.
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string path = Path.Combine(desktop, "LS\\Fail-SafePath.dat");
openFileDialog.InitialDirectory = filePath;
openFileDialog.Filter = " PlayGTAV (*.exe)|PlayGTAV.exe";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
var fileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(filePath);
}
After that that i have a start button for it
private void panel21_MouseClick(object sender, MouseEventArgs e)
{
Process.Start(filePath);
}
This works well when the user does it for the first time but now I want it to read that .dat file path automatically without having to ask the user for the file path every single time which I don't know how to do and need help with please.
I was thinking to do it like that: When Pressing the Launch button (After the first time) The Program Checks if the Fail-SafePath.dat Exists if Yes it reads the lines from it and starts the program from the given path without opening OpenFileDialog.
I'm Using Visual Studio, Windows Form.
If it's a file that the application will always need, then something like you mentioned:
I was thinking to do it like that: When Pressing the Launch button (After the first time) The Program Checks if the Fail-SafePath.dat Exists if Yes it reads the lines from it and starts the program from the given path without opening OpenFileDialog.
Could work easily enough. You could have your application look for it in the default location, and if not there, have your user select it.
Another solution could be using something like Application Settings or User Settings, which are values persisted between executions of .NET projects.
Depending on your full application design, you could also have the file path and other settings stored in some database or other data storage. There are a lot of ways to accomplish this.
EDIT: To elaborate further on the Application Settings
The application settings are very easy to read and write to.
You just need to create the ones you want, before trying to use them.
They can be created by:
Open Visual Studio.
In Solution Explorer, expand the Properties node of your project.
Double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.
In the Settings designer, set the Name, Value, Type, and Scope for your setting. Each row represents a single setting.
To read from your settings:
this.FilePath= Properties.Settings.Default.FilePath;
To write to and save the setting:
Properties.Settings.Default.FilePath= Path.GetFullPath("importantFilePath");
Properties.Settings.Default.Save();

Export text to a browsed file in wpf

I'm trying to export some text to a file browsed by the user and create it if this file does not exists.
What I've done till now is to use OpenFileDialog but I don't know if it's the right way to do it and also if it is I don't know how to continue
You can use the SaveFileDialog()
var dialog = new SaveFileDialog();
dialog.ShowDialog();
var path = dialog.FileName;
File.WriteAllText(path, "YourData");

C# OpenFileDialog open zip folder containing single file?

I have an application which currently provides the user with the ability to view a PDF file inside the application by using File->Open, browsing to the location of the PDF file using a Microsoft.Win32.OpenFileDialog, and then displaying that PDF file in a System.Windows.Controls.WebBrowser in the GUI.
I am creating the OpenFileDialog and setting the file extensions it can open using:
/*Create Open File dialog */
Microsoft.Win32.OpenFileDialog OFDlg = new Microsoft.Win32.OpenFileDialog();
/*Set filter for file extension and default file extension */
OFDlg.DefaultExt = ".pdf";
OFDlg.Filter = "PDF Documents (.pdf)|*.pdf";
I now want to extend this, so that the user can open a ZIP folder containing a single PDF document, and display that PDF document in the same way that I am above.
I tried changing the filter to allow .zip files, i.e.
OFDlg.DefaultExt = ".pdf|.zip";
OFDlg.Filter = "PDF Documents (.pdf)|*.pdf|ZIP|*.zip";
but when I browse to the location of the .zip file in the OpenFileDialog, the .zip folder is not displayed there- only normal folders and PDF documents (other documents in that directory, such as .doc & .xls are not displayed in the OpenFileDialog).
My reason for wanting to be able to open the contents of a .zip file directly from the .zip, rather than navigating to that file itself, is so that I can add public/private key encryption to the .zip, so that its contents can only be read securely.
I know that there could in theory be problems if the .zip contains more than one file, but I intend to send each encrypted file in its own zip folder, so it can be assumed that any zip file that the user is trying to open contains a single .pdf, and nothing else.
So my questions are:
How can I make .zip folders visible from the OpenFileDialog?
How can I make the selection of that .zip folder automatically open and display its contents (a single PDF file) in the System.Window.Controls.WebBrowser that I am currently using to display PDFs in my GUI?
Edit 1
I tried changing my OpenFile() method to the following code:
/*Set filter for file extension and default file extension */
OFDlg.DefaultExt = ".pdf";
OFDlg.DefaultExt = ".zip";
OFDlg.Filter = "PDF Documents (.pdf)|*.pdf";
OFDlg.Filter = "ZIP Folders (.ZIP)|*.zip";
but when I now run my application, and browse to the same location, although the .zip folder is now shown in the OpenFileDialog, the .pdf files no longer are... and if I double click the .zip folder, my application breaks, and I get a runtime error on the line
PdfPanel.OpenFile(docFP);
which says:
An unhandled exception of type 'System.AccessViolationException' occurred in MoonPdfLib.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I guess that's to do with the MoonPDF library that I'm using to read the PDFs being unable to handle the .zip extension?
How would I resolve this to be able to open the PDF inside the ZIP?
Edit 2
Ok, so I've resolved the issue about only being able to see either the PDF files or the .ZIP folders (not both at the same time), by moving the functionality into two separate methods- one to display the PDF direct from the PDF's filepath, and another to display the PDF from the path of the .ZIP folder holding it.
The method for displaying the PDFs directly currently works (it is essentially the code in the first bit of code I've quoted). However the method for displaying the PDFs from the ZIP currently doesn't work...
I understand the reason for this- it's because I am passing a .zip folder to the OpenFile method... The code for this method currently looks like this:
private void openZipMenuItem_click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog OZipDlg = new Microsoft.Win32.OpenFileDialog();
OZipDlg.DefaultExt = ".zip";
OZipDlg.Filter = "ZIP Folder (.zip)|*.zip";
Nullable<bool> result = OZipDlg.ShowDialog();
if (result == true)
{
/*Open document */
string filename = OZipDlg.FileName;
//fnTextBox.Text = filename;
zipFP = OZipDlg.FileName;
/*browser.Navigate(docFP); ERF (27/05/2016 # 0935) Comment this line- I want to use PdfPanel to open docFP, not browser */
Console.WriteLine("Panel height: " + PdfPanel.ActualHeight);
PdfPanel.OpenFile(zipFP);
}
}
When I try to call this function to open a .zip, I get a runtime exception which says:
AccessViolationException was unhandled
An unhandled exception of type 'System.AccessViolationException' occurred in MoonPdfLib.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I understand that I can't display a Zip folder in the PdfPanel (which is a MoonPdfPanel that I am using from the MoonPdfLibrary), so I know that I will get an exception here.
How can I pass the contents of zipFP to the call to PdfPanel.OpenFile(), rather than passing zipFP itself to it?
Edit 3
Ok, so my code is currently extracting the PDF file successfully from the ZIP folder when I open it- I can see that it is copied to the directory I have specified. I am now trying to get the PDF to be displayed automatically in the PDF Panel on my application- I've done this by adding the following code:
try{
string extractPath = #"C:\Documents";
using(ZipArchivev zip = ZipFile.Open(zipFP, ZipArchiveMode.Read))
foreach(ZipArchiveEntry entry in zip.Entries){
try{
ZipFile.ExtractToDirectory(zipFP, extractPath);
Console.WriteLine("zipFP: " + zipFP);
}catch(System.IOException){
Console.WriteLine("File already exists...");
}
}
string ExtractedPDF = string.Concat(extractPath, zipFP);
PdfPanel.OpenFile(ExtractedPDF);
}catch(AccessViolationException ex){
Console.WriteLine("Can't display a zip in the PDF panel..." + ex.InnerException);
}
But when my code tries to execute the line PdfPanel.OpenFile(ExtracedPDF);, I get an exception that says:
FileNotFoundException was unhandled | An unhandled exception of type 'System.IO.FileNotFoundException' occurred in MoonPdfLib.dll'
I understand that this is happening because the variable I am trying to display in the PDFPanel, ExtractedPDF actually holds the path of the folder containing the PDF, and not the PDF itself- How do I give it the name of the PDF file, when I don't actually know what the PDF file will be called?
Here is something works similar to your requests, the logic behind the code is:
Only display zip and pdf files in the OpenFileDialog
If user selected a pdf file, show it in the panel
If user selected a zip file, change the directory of the OpenFileDialog to the zip file(treat it like a folder)
Example code (working code....):
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF files (.pdf)|*.pdf;*.zip";
ofd.ShowDialog();
//reopen OpenFileDialog if it is zip file. this part can be improved.
if (ofd.FileName.EndsWith(".zip"))
{
ofd.InitialDirectory = ofd.FileName;
ofd.ShowDialog();
}
//if it's a PDF, note that you don't really need this check,
//as the only file can reache here will be a PDF,
//and it can be the temporary file that inside a zip.
if(ofd.FileName.EndsWith(".pdf"))
{
//show it in your PdfPanel
}
Edit, based on your new comments and added code. you need to change your code to the following as your current code is mistaken directory with the file:
try{
string extractPath = #"C:\Documents";
string ExtractedPDF ="";
using(ZipArchivev zip = ZipFile.Open(zipFP, ZipArchiveMode.Read))
foreach(ZipArchiveEntry entry in zip.Entries){
try{
ExtractedPDF= Path.Combine(extractPath, entry.FullName);
entry.ExtractToFile(ExtractedPDF,true);
}catch(System.IOException){
Console.WriteLine("error during extraction...");
}
}
if( System.IO.File.Exists(ExtractedPDF))
{
PdfPanel.OpenFile(ExtractedPDF);
}
}catch(AccessViolationException ex){
Console.WriteLine("Can't display a zip in the PDF panel..." + ex.InnerException);
}
If you want to support multiple file formats in an open file dialog, you need to add a third (or better first) option, that aggregates all supported file extensions:
OFDlg.Filter = "Supported file formats|*.pdf;*.zip|PDF Documents|*.pdf|ZIP files|*.zip";
First, regarding showing the files in the open file dialog. Your initial method for doing this was correct. Your updated code now first sets the filter to show PDFs, then replaces that filter with one that shows zip files. The standard file open dialog isn't designed to show different file types at the same time. The right way to handle that is to give the user the option for which file types they want to show.
Typically, an "All files" option is added as well (with . as the search pattern). This way if the file type the user wants to open isn't available in the list, they can see it regardless.
As for opening the PDF file that is in the zip file, you need to take are of extracting the PDF file yourself. This question has some options for how to do that.

OpenFileDialog xml Filter allowing .htm shortcuts

I've filedialog in winforms.
It is set to read only .xml files.
ofd.DefaultExt="xml";
ofd.Filter="XML Files|*.xml";
but when I run it is allowing to upload .htm file shortcut. whereas it should not show .htm file at all.
You're doing it correctly. Using the Filter property allows you to limit the files displayed in the open dialog to only the specified type(s). In this case, the only files the user will see in the dialog are those with the .xml extension.
But, if they know what they're doing, it's trivial for the user to bypass the filter and select other types of files. For example, they can just type in the complete name (and path, if necessary), or they can type in a new filter (e.g. *.*) and force the dialog to show them all such files.
Therefore, you still need logic to check and make sure that the selected file meets your requirements. Use the System.IO.Path.GetExtension method to get the extension from the selected file path, and do an ordinal case-insensitive comparison to the expected path.
Example:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML Files (*.xml)|*.xml";
ofd.FilterIndex = 0;
ofd.DefaultExt = "xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
if (!String.Equals(Path.GetExtension(ofd.FileName),
".xml",
StringComparison.OrdinalIgnoreCase))
{
// Invalid file type selected; display an error.
MessageBox.Show("The type of the selected file is not supported by this application. You must select an XML file.",
"Invalid File Type",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
// Optionally, force the user to select another file.
// ...
}
else
{
// The selected file is good; do something with it.
// ...
}
}

Categories