Saving the opened file in particular folder - c#

I have a dropdownlist and a textbox. When i write some name and select some options in dropdownlist like word or excel or powerpoint, that particular file opens as an attachment and i should save it in "data" folder which is already present in the solution explorer. My code is like this
string file = TextBox1.Text;
if (dd1.SelectedIndex == 1)
{
Response.ContentType = "application/word";
Response.AddHeader("content-disposition", "attachment;filename =" + file + ".docx");
}
How can I store this file in "data" folder?

The simple answer is "you cannot". Saving file is taking place on the client side. Your web application knows nothing about the client machine (not even whether it's a real browser or another script) and has no control over the client. The end user will have to manually select data folder to save the file to.

Related

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.

Delete .doc duplication during PDF conversion c#

I currently have a program that merges a folder consisting of word docs into one combined file via user input with a FileBrowserDialog. Once files are selected, a 'combine' button applies the code shown below which sources the folder containing the documents, output location and name of the file created.
string fileDate = DateTime.Now.ToString("dd-MM-yy");
string fileTime = DateTime.Now.ToString("HH.mm.ss");
string outcomeFolder = outputFolder;
string outputFileType = ".docx";
string outputFile = "Combined Folder " + fileDate + " # " + fileTime + outputFileType;
string outputFileName = Path.Combine(outcomeFolder, outputFile);
// Combines the file name, output path selected and the yes / no for pagebreaks.
MsWord.Merge(sourceFiles, outputFileName, pageBreaker);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);}
The MsWord referenced calls a separate .CS file which combines the folder components, output name and a boolean to enable page-breaks. The MsWord also automatically saves the word .doc to the user specified location once the contents of the folder are successfully combined. MsWord.Merge(sourceFiles, outputFileName, pageBreaker);
The issue i'm wanting to address is, when I enable this check box:
if (convert2PDFBox.Checked)
Microsoft.Office.Interop.Word.Application officeApp = new Microsoft.Office.Interop.Word.Application();
officeApp.Documents.Open(outputFileName);
outputFileType = ".pdf";
officeApp.ActiveDocument.SaveAs(outputFileName + outputFileType, WdSaveFormat.wdFormatPDF);
officeApp.Quit();
I want the program to solely create a PDF of the combined folder and not 2 seperate .doc and .PDF files, which it currently does. Since the MsWord.save function is called separately and is essential to the overall function of my program, I was wondering is there a possibility of deleting the initially combined file once conversion of the PDF takes place? e.g. "combinedDocument".Delete - Essentially allowing the copy to take place however not presenting the user with the initial .doc - only the .PDF
Though the issue is small, I would love to get it addressed and welcome any suggestions or advice with this manner. I can also provide any additional information if needed, thank you.
tl;dr - merging program creates an amalgamated Word .doc, which i want to change solely to a PDF when a checkbox is enabled instead of creating a .doc and PDF.
I finally resolved my issue - What I decided to do was manipulate my existing MsWord.cs and create a separate PDF.cs call for my main form:
Rather than save the Word .doc when being merged, I instead used: wordApplication.ActiveDocument.SaveAs(outputFile, Word.WdSaveFormat.wdFormatPDF);
which saved the merged content thus far as a .pdf
This however presented errors with Microsoft Word as I was then prompted to 'Save File As' due to the merged file never actually being saved in a .Doc / .Docx format
I then altered the closing statement of the call,
// Close Word application
wordApplication.Quit(
false, // save changes
By setting the 'Save Changes' setting to False, it removed the 'Save As' prompt which allowed the Word doc. to be dismissed without needing to be saved, thus leaving only the initial PDF created. I then applied the two separate File type calls to each checkbox presented, which allowed the user to enable the outcome format of the merged files.
Thank you for the suggestions regarding the issue.

How to rename files before upload

I need to rename every file uploaded using dropzone.js to add a timestamp in his name.
I already tried to do this in the server side, but I can't recover the modified name and set it into the script to do a deletion on server when file is deleted on the browser.
I tried to rename the file int the script too, before upload, but unsuccessful. The functions I tried to use are these:
accept: function (file, done) {
file.name = "timestampHere" + file.name;
done();
}
And this:
sending: function (file, xhr, formData) {
file.name = "heee" + file.name;
}
But in both cases, I can't recover the file name and change it to proceed a file delete on the server when the "Remove" button is fired.
In other words, the file in the server have the time stamp and in browser doesn't.
There's any way to recover the name of the file saved on the server and set it into the script on the browser OR rename the file in the script, before the upload?
My target here is to delete the file on the server too on click of the "Remove" button, after inserting timestamp in the name of the file.
I found an answer here: https://stackoverflow.com/a/17457380/2394172
The context is different of mine, but I've used his concept, creating a repository with an array of objects containing the original name and the server name.
With this I can compare the values and send to the server just the server value.
I hope this can help someone.

Mapping Uploaded Files to different directory

Using AjaxFileUpload
string path = Server.MapPath("~/Files/") + e.FileName;
This code is uploading files to Files directory under Website folder in asp.net...
How i can map uploaded files to different directory ?
e.g.
Combo Box -> have two option
Image
Doc .
If a user select Image then files uploaded should move to Image folder ..similarly for Doc..
How to write code for this in asp.net c# ?
You just need a conditional to check which option they have selected then place them accordingly. The following code assumes the directories exist, if that's not the case then you'll have to add some logic to create them in the event that they don't.
string path = System.String.Empty;
if (image == true)
path = Server.MapPath("~/Files/Images") + e.FileName;
else
path = Server.MapPath("~/Files/Docs") + e.FileName;
More likely you'll have to do some logic to group them based the file extension. Another option would be to put a radio button for image, in on click listener where the user submits the image you can check whether or not that option is set (my code sample is expecting something like this).

save as dialog in asp.net

I have some data in the form of a string. I want to write this data to a file and save the file to the specified path. The path would be specified by opening a save as dialog on the button click. How can this be achieved??
The file is saved into the server initially with this code
string getnote = txtdisplay.Text.Trim();
String filepath = Server.MapPath(#"img\new1.txt");
System.IO.FileStream ab = new System.IO.FileStream(filepath, System.IO.FileMode.Create);
System.IO.StreamWriter Write101 = new System.IO.StreamWriter(ab);
Write101.WriteLine(getnote);
Write101.Close();
Response.ClearContent();
From the server get the file as attachment.Use the following code for save as dialog box for downloading or saving the file. The file will save by default in the download folder. To save to the specified location change the browser settings.
Response.ContentType = "text";
Response.AppendHeader("Content-Disposition", "attachment; filename=new1.txt");
Response.TransmitFile(Server.MapPath("~/img/new1.txt"));
Response.End();
Response.ContentType = "application/octet-stream" (or content type of your file).
Response.AppendHeader("content-disposition", "attachment;filename=" & strFileName)
There is no Save As dialog in ASP.NET.
Remember, your ASP.NET application is running in a browser on a user's computer. You have no access to the user's file system, including the Save As dialog.
However, if you send the user a file, as an attachment, most browsers will display a dialog asking the user whether to save the file or open it. Maybe the user will choose to save it. That's what the example from phoenix does.
You could use a LinkButton (or regular link) and have the url point to a handler (ASHX) that retrieves the data and sends back a response with content disposition set to attachment. Write the data to the response. You'll also need to set up some other headers in the response -- such as content type and length. This would give the document (file) a regular link that could perhaps be bookmarked (if a regular link) in the future so that it can be retrieved again. You'd need to pass enough data in the query string to be able to identify which data is to be downloaded.
if I userstand you correctly, here -
saveFileDialog1.DefaultExt = "*.file";
saveFileDialog1.Filter = "File|*.file|Other File|*.OFile|";
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFileDialog1.FileName.Length > 0)
{
WebClient wc = new WebClient();
wc.DownloadFile("http://www.exaple.com/exaplefile", saveFileDialog1.FileName);;
}

Categories