C# LoadFile throwing unhandled exception when loading .txt, .rtf - c#

I'm learning C# and went through a text editor tutorial. The final result works pretty good, except there is something strange happening I do not understand.
When I write/save/load files all in the text editor they work fine. But whenever I write a file in a different editor/download a text file from the internet somewhere, the file fails to load.
When I load the file, I get
"An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll"
And when I look at "View Details" is says
"File format is not valid."
Even though there is text in the file (when viewed in a different text editor), the text property has nothing in it, a result of the file format being incorrect.
I'm pretty confused why it would load files made in the text editor itself (with the same extension) but not from somewhere else. I'm really not sure how to begin debugging this one. My save file/open file methods are listed below.
Open File
private void Open()
{
openFileDialog1.Filter = "RTF|*.rtf|Text Files|*.txt|VB Files|*.vb|C# Files|*.cs|All Files|*.*";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && openFileDialog1.FileName.Length > 0)
{
GetCurrentDocument.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
Save File
private void Save()
{
saveFileDialog1.FileName = tabControl1.SelectedTab.Name;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "RTF|.rtf";
saveFileDialog1.Title = "Save";
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (saveFileDialog1.FileName.Length > 0)
{
GetCurrentDocument.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
}
Help would be much appreciated, thanks!

It's not just the extension of the file that determines it's type. This version of the method allows loading both "regular" RTF files and also ASCII files.
The RichTextBoxStreamType Enumeration provides a few different possibilities. If you are trying to load a file created using a different editor, you might need to use RichTextBoxStreamType.PlainText instead of RichTextBoxStreamType.RichText.

Related

Why my OpenFileDialog didnĀ“t work?

I try to open a textdocument and then I get the message: invalid file format from the try-catch. I use Visual Studio 2015 with Visual C# and Windows Forms Application.
Here my code for the open function:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
try {
// Create an OpenFileDialog to request a file to open.
OpenFileDialog openFile1 = new OpenFileDialog();
// Initialize the OpenFileDialog to look for RTF files.
openFile1.Filter = "Text Files (*.txt)|*.txt| RTF Files (*.rtf)|*.rtf| All (*.*)|*.*";
// Determine whether the user selected a file from the OpenFileDialog.
if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
openFile1.FileName.Length > 0)
{
// Load the contents of the file into the RichTextBox.
TextBox.LoadFile(openFile1.FileName);
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
}
}//end open
I hope you can help me with friendly wishes sniffi.
The problem is probably that you don't load a RTF document - see the docs on MSDN.
With this version of the LoadFile method, if the file being loaded is
not an RTF document, an exception will occur. To load a different type
of file such as an ASCII text file, use the other versions of this
method that accept a value from the RichTextBoxStreamType enumeration
as a parameter.
So try to use the overloaded version of this method which accepts the stream type like so (adjust to your needs)
TextBox.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);

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.

Get full file path including file's name from an uploaded file in C#

I have this web application project which requires a better user-interface and I am doing it by C#.
I already have my html file with JS done but I need some data from user.
In my JS embedded in HTML file, I used the code below to find the file on local driver and get the data from that excel file and then put all these data into an array.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open(file1);
var excel_sheet = excel.Worksheets("Sheet1");
However, the "file1" you see above seems to require a full name path,say "C:\test.xls" in my case.
I am new to C# and just built a button on my form design, by clicking the button, I seem to be able to browse my local file.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
System.Diagnostics.Process.Start(file);
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
So, my question:
How can I get this kind of full file path of an uploaded file in C# ?
And furthermore, it would be awesome if some one can tell me how to get this value into my javascript or HTML!
Thank you in advance
You won't be able to depend on getting the full path. In the end, the browser only needs to multi-part encode the physical file and submit it as a form post (of sorts). So once it has it's location and has encoded it -- it's done using it.
It's considered a security risk to expose the file structure to Javascript/HTML (ie., the internet).
Just an update.
I used another logic and it worked as expected. Instead of getting absolute file path , I managed to open the file , save it as somewhere and make my html call find that file path no matter what.

trouble saving bitmap to file in C#

I'm trying to save a bitmap to a file, all the examples and tutorials I have found suggest using this line of code to do so-
private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) // Save the fractal image
{
SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
fractal.Save("myfile.png", ImageFormat.Png);
}
}
When I execute the code by click the save image button (which calls the above method) a save dialog appears but both the file name field and file type field are empty. I select a location to save to and give the file a name - e.g. bitmap.png then check the location and nothing has saved.
I have also checked the debug folder and nothing has appeared there ether.
I'm assuming I'm not far off or that I've made a silly mistake elsewhere any ideas or suggestions?
Assuming you are using the SaveFileDialog class, you need to set the Filter and DefaultExt properties to get the file extensions to show up.
You then read the FileName property as the argument to your Save() call

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