How to create a file on server and save it on server - asp.net

I m creating a pdf file on the server using iTextSharp.
It is working fine prompting me to save everything is fine.
I have 2 scenario
1) I want to save this file on a location on server
2) I want to save this file in database
My Last line after finishing the code is
document.Close();
So can anyone guide me how can I do it

The following method will create a new file on the disk with a paragraph in it. You could easily modify it to your needs.
Before this will work you must ensue the directory you wish to save to has the correct permissions set. Whatever user account the Application Pool for the website is using will need write access to the folder. Set this in Windows Explorer, Right Click > Properties > Security Tab. This is well documented on the internet.
You can store the filename in the database in many different ways and then link to the file from your UI. I suggest starting with a simple ADO.Net tutorial
protected void CreateDoc(string filename)
{
Document document = new Document();
PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
document.Open();
document.Add(new Paragraph("Hello World!"));
document.Close();
}

Related

Download a file on the client macine using asp.net

I want to download a text file from my website to the users pc without prompting him for the location to save the file.
I have tried it using code below :
Response.TransmitFile("G:\Medical Reporting\Medical\Users\Vishal\Uploaded\Key.txt")
Response.End()
But every time I am just redirected to the new page and all the contents of the file is written there. I don't want to display the contents of the file, but I want to download the file.
Not possible - it's a security issue, otherwise the world would be trying to save all sorts of files on a users machine.
If it's an intranet each user could have a shared drive on a network accessible to the web app and simply copy the file using IO.File.Copy method.
Update
To Prompt a user to download a file you can use the following code which will be fired after clicking something like a button:
this example is for an image, though you can just change the ContentType filename to suit your needs.
Response.ContentType = "image/jpeg";
// this is the important bit that gives the user the prompt to save
Response.AppendHeader("Content-Disposition","attachment; filename=yourfile.jpg");
Response.TransmitFile(Server.MapPath("~/yourfile.jpg"));
Response.End();

Download and run file in client machine using asp.net

I'm trying to download and run a file to the client machine. The client is aware of that.
It's a ttkgp file that's dynamicly generated.
I've tried using Processs.Start() that worked fine on my local machine (first saved the file to C:\ then lunched it), but it's not working from the server. It's not my server but a hosted one. They are trying to help but no luck so far.
I've seen this code:
public void ProcessRequest(HttpContext context)
{
string fileName = context.Request.QueryString["filename"];
FileInfo fi = new FileInfo(fileName);
context.Response.ContentType = "application/x-rar-compressed";
context.Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename=download{0}", fi.Name));
context.Response.WriteFile(fileName);
context.Response.End();
}
But since I dont know what's "HttpContext context" is, I've no idea if it works.
Is it some server previlges need to be changed? or simply this code will do the trick?
Thank you
UPDATE (24.6.12): I'm nearly finished with the problem, all I need now is to know how to open an html page in a new tab / window and close it second later. Once I'm done, I'll post back here all the process, I'm sure it'll help other people.
UPDATE (26.6.12):
Here's what I've got:
The goal is to download an TTKGP file from asp.net webiste to local user machine and run it.
Step 1: generate the file with code behaind (c#) on the server (V)
Step 2: copy the file or it's content to user machine (X)
Step 3: run the file using JS (V)
Here's the thing: I CAN copy from a text file on the server to a text file on the user machine, but not from TTKGP files. It's strange because this are just text files just a different extantion.
The code for copying text files:
enter code here
function copyremotetxt() // works
{
// copy the txt file
var fso = new ActiveXObject("Scripting.FileSystemObject");
var newfile = fso.CopyFile("remote.txt", "C:\\Users\\***\\local.txt");
}
Perhaps I can change the file type on the user machine?
Notice 1: I know that's a security issue, the site is just for known user not the open public
Notice 2: I know there are better ways to get the task done, but there are strict limitaions on many things
Thanks for those how can help!!
This code will do the trick. It will prompt the client to download and save the file on his computer at the location he decides. What happens next with this file is the client's decision, not yours. He might simply close the Save As dialog, interrupt the download, delete the file, ... It's up to him.
Another remark: this code is extremely dangerous because it allows the client to pass any filename he wants as query string parameter and download it. So he could read absolutely all files on the server which is probably not something that you want to happen.
Ok, this need a different aproach.
I'll try using JavaScript do read the file on the server, rewrite it in the user machine and activate it. Any clues would be grate! For a start, how to I read file in JS? I'm new to it.

ASP.NET Generating .pdf files, UnauthorizedAccessException on Save()

I have a list of jobs and i give users the option to get job description in form of a pdf file. I use MigraDoc/PDFsharp to generate pdf files.
The problem is, after i render the pdf document and want to save it somewhere on the DevServer i get UnauthorizedAccessException on creating FileStream in PDFsharp PdfDocument.Save() method.
I never really used Windows for anything more advanced than playing games and i'm not sure why would i get this exception since i'm logged in as Administrator user and i guess that my ASP.NET application is running with Administrator privilleges and should be able to write files pretty much anywhere on filesystem.
The Code.
GridViewRow jobRow = (GridViewRow)(sender as Control).Parent.Parent;
Document jobDocument = new Document();
Section xyz = jobDocument.AddSection();
xyz.AddParagraph("Wonderfull job");
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true);
pdfRenderer.Document = jobDocument;
pdfRenderer.RenderDocument();
string filename = "Job_" + jobRow["3"] + ".pdf"; // Job_[title].pdf
pdfRenderer.PdfDocument.Save(filename);
Last line is the line that causes the exception.
Any suggestions? I'm not an ASP.NET developer and I'm forced to use ASP.NET for my school project so this may be a very simple problem but i really don't know what to do and what to search. Thanks for answering!
Administrator account =! IIS user.
The IIS User needs to have writing privileges, too!
On most machines it is know as "IIS_User" or maybe "network service". First you can grant writing permissions to every User. If this works for you, you know what to do.
First try to set an absolute path as filename, maybe a directory outside of "C:\inetpub\wwwroot"?
Hope this helps!

Read file without exclusive lock

What is the best way to read image when simultaneous requests try to access the same image file?
Basically I have created tiff viewer in asp.net. It displays thumbnails of all tiff pages and upon click loads full image below. But when I try to read big tiff file (40+ MB), some thumbnails shows up and some throw access denied error. I hope I am clear enough to explain the problem.
you should open the Stream in this way:
using (Stream s = new FileStream(fullFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
// here use the stream s
}
in this way you open for read and still other processes will be able to read the file as well and only one process, not yours, could eventually acquire the write rights.
see here as well: How do I open an already opened file with a .net StreamReader?

Aspx file generation

I am working on an .aspx page.its to download a pdf that is generated in the aspx page.
.but when hosted in Amazon cloud i am getting the message.
"The process cannot access the file because it is being used by another process".
but on the subsequent invocation of the .aspx page i am getting the pdf .
The pdf file is being generated.
Asp.Net uses separeted threads for each request. Probably you use some shared resources to generate pdf and don't clean up them. Therefore parellel requests may fail.
Using block (or calling Dispose() directly) may help.
using (StreamReader reader = new StreamReader(#"C:\My Files\test.txt"))
{
..
}
Also make sure you don't open files with exclusive permissions like this:
FileStream fileStream = new FileStream("test.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None);

Resources