I am looking to allow a person to to export journal entries into a text file. I can create a file with all the data but rather strictly saving the file somewhere specific I want to allow a user to download and save the file where they want on their computer. How to I force a download of a file after I create it with StreamWriter. I currently have the following code:
string fileName = "Journal.txt";
using (StreamWriter journalExport = new StreamWriter(fileName))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
I am also trying to put this into an ActionResult and return the file.
EDIT:
The following code is my new current code and the direction I am looking to go in, but when I use an ActionLink to call this method, i just get redirected to a new page rather than downloading the file.
string fileName = "Journal.txt";
string filepath = ConfigurationManager.AppSettings["DocumentRoot"] + "\\" + id + "\\" + fileName;
using (StreamWriter journalExport = new StreamWriter(filepath))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
byte[] fileData = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, contentType);
This might be what you are looking for:
public ActionResult GetFile()
{
...processing stuff...
return File("/files/file.pdf", "application/pdf");
//or
return File("/files/file.pdf", "application/force-download", "donwloadname.pdf");
}
I am using the following code to export a crystal report in pdf format.
if (textBox1.Text == "" | textBox2.Text == "")
{
}
else
{
string filename = "\\" + textBox1.Text + ".pdf";
CreateEmptyFile(filename);
string file = textBox2.Text + "\\" + textBox1.Text + ".pdf";
labelget();
try
{
int idx = dataGridView1.CurrentCell.RowIndex;
string parv = dataGridView1.Rows[idx].Cells[0].FormattedValue.ToString();
ReportDocument wordreport = new ReportDocument();
wordreport.Load(#"C:\\FOLDER\\TESTREPORT.rpt");
wordreport.SetDatabaseLogon("root", "xxxxxxx", localhost, database);
wordreport.Refresh();
wordreport.SetParameterValue("bill_no", parv);
wordreport.SetParameterValue("fromterminal", this.terminal);
wordreport.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, file);
}
catch (Exception em)
{
MessageBox.Show("error is: " + em);
}
}
Error Occurs in line wordreport.ExportToDisk saying the system could not find the specified path. I checked the permissions for the path where I created the PDF file, It all looks good.
How do i rectify this error?
I Found the Reason and answer for my question. I missed to add DSN details in admin tools.
I'm trying to upload a file and change its name below. I need to get the file extension. The code below has a underline under "Path" am I missing a using statement? Or what is the correct syntax for what I'm doing?
if (FileUpload1.HasFile)
try
{
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
var newName = DateTime.Now.ToLongDateString();
//Map path to folder
string realpath = Server.MapPath("Pictures\\") + Guid.NewGuid() + FileExtension;
FileUpload1.SaveAs(realpath);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
//Handle the error
throw ex;
}
else
{
Label1.Text = "You have not specified a file.";
}
FileInfo fi = new FileInfo(fileName);
string ext = fi.Extension;
"Path" am I missing a using statement?
You have to add
using System.IO;
to the list of namespaces
The code you have provided looks fine (and works on my machine).
The only thing I can see that you might be missing is the using statement for System.IO.
Use this code:
string extension=System.IO.Path.GetExtension(file1.FileName);
im using a file upload control and here is my code :
//Uploading the image
if (imageUpload.HasFile)
{
try
{
if (imageUpload.PostedFile.ContentType == "image/jpeg")
{
if (imageUpload.PostedFile.ContentLength < 102400)
{
string im = ( "~/User" + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".jpeg");
imageUpload.SaveAs(im);
uploadLabel.Text = "";
}
else
{
uploadLabel.Text = "File size must be less than 1024 kb";
}
}
else
{
uploadLabel.Text = "File must be in jpeg/jpg format";
}
}
catch(Exception ex)
{
uploadLabel.Text = "File upload failed becuase: " + ex.Message;
}
}
but im getting an error:
The SaveAs method is configured to require a rooted path, and the path "path" is not rooted.
what am i doing wrong.
thanks
SaveAs() requires an absolute path.
try using Request.PhysicalApplicationPath + "\\User"
The Save method is configured to require an absolute path (starting with X:\..., in some drive).
You should call Server.MapPath to get the absolute path on disk to ~/whatever.
Add Server.MapPath where you declare im
Server.MapPath gives you the absolute path.
string im = Server.MapPath("/User") + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".jpeg";
string filename = FileUpload1.FileName.ToString();
if (filename != "")
{
ImageName = FileUpload1.FileName.ToString();
ImagePath = Server.MapPath("Images");
SaveLocation = ImagePath + "\\" + ImageName;
SaveLocation1 = "~/Image/" + ImageName;
sl1 = "Images/" + ImageName;
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
try this may be help ful.......
I am working on an application. That application should get the resume from the users, so that I need a code to verify whether a file exists or not.
I'm using ASP.NET / C#.
You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:
bool System.IO.File.Exists(string path)
You can find the documentation here on MSDN.
Example:
using System;
using System.IO;
class Test
{
public static void Main()
{
string resumeFile = #"c:\ResumesArchive\923823.txt";
string newFile = #"c:\ResumesImport\newResume.txt";
if (File.Exists(resumeFile))
{
File.Copy(resumeFile, newFile);
}
else
{
Console.WriteLine("Resume file does not exist.");
}
}
}
To test whether a file exists in .NET, you can use
System.IO.File.Exists (String)
if (File.Exists(Server.MapPath("~/Images/associates/" + Html.DisplayFor(modelItem => item.AssociateImage))))
{
<img src="~/Images/associates/#Html.DisplayFor(modelItem => item.AssociateImage)">
}
else
{
<h5>No image available</h5>
}
I did something like this for checking to see if an image existed before displaying it.
Try this:
string fileName = "6d294041-34d1-4c66-a04c-261a6d9aee17.jpeg";
string deletePath= "/images/uploads/";
if (!string.IsNullOrEmpty(fileName ))
{
// Append the name of the file to previous image.
deletePath += fileName ;
if (File.Exists(HttpContext.Current.Server.MapPath(deletePath)))
{
// deletevprevious image
File.Delete(HttpContext.Current.Server.MapPath(deletePath));
}
}
Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.
You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.
<asp:FileUpload ID="FileUpload1" runat="server" />
They then pick a file to upload, and you have to deal with any empty file that they might send up server side.
You could use:
System.IO.File.Exists(#"c:\temp\test.txt");
Can't comment yet, but I just wanted to disagree/clarify with erikkallen.
You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.
In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().
I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.
These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.
The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)
You wrote asp.net - are you looking to upload a file?
if so you can use the html
<input type="file" ...
In addition to using File.Exists(), you might be better off just trying to use the file and catching any exception that is thrown. The file can fail to open because of other things than not existing.
This may help you.
try
{
con.Open();
if ((fileUpload1.PostedFile != null) && (fileUpload1.PostedFile.ContentLength > 0))
{
filename = System.IO.Path.GetFileName(fileUpload1.PostedFile.FileName);
ext = System.IO.Path.GetExtension(filename).ToLower();
string str=#"/Resumes/" + filename;
saveloc = (Server.MapPath(".") + str);
string[] exts = { ".doc", ".docx", ".pdf", ".rtf" };
for (int i = 0; i < exts.Length; i++)
{
if (ext == exts[i])
fileok = true;
}
if (fileok)
{
if (File.Exists(saveloc))
throw new Exception(Label1.Text="File exists!!!");
fileUpload1.PostedFile.SaveAs(saveloc);
cmd = new SqlCommand("insert into candidate values('" + candidatename + "','" + candidatemail + "','" + candidatemobile + "','" + filename + "','" + str + "')", con);
cmd.ExecuteNonQuery();
Label1.Text = "Upload Successful!!!";
Label1.ForeColor = System.Drawing.Color.Blue;
con.Close();
}
else
{
Label1.Text = "Upload not successful!!!";
Label1.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ee) { Label1.Text = ee.Message; }
I have written this code in vb and its is working fine to check weather a file is exists or not for fileupload control. try it
FOR VB CODE ============
If FileUpload1.HasFile = True Then
Dim FileExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
If FileExtension.ToLower <> ".jpg" Then
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "Please select .jpg image file to upload"
Else
Dim FileSize As Integer = FileUpload1.PostedFile.ContentLength
If FileSize > 1048576 Then
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File size (1MB) exceeded"
Else
Dim FileName As String = System.IO.Path.GetFileName(FileUpload1.FileName)
Dim ServerFileName As String = Server.MapPath("~/Images/Folder1/" + FileName)
If System.IO.File.Exists(ServerFileName) = False Then
FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File : " + FileName.ToString() + " already exsist"
End If
End If
End If
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "Please select a file to upload"
End If
FOR C# CODE ======================
if (FileUpload1.HasFile == true) {
string FileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (FileExtension.ToLower != ".jpg") {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select .jpg image file to upload";
} else {
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize > 1048576) {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File size (1MB) exceeded";
} else {
string FileName = System.IO.Path.GetFileName(FileUpload1.FileName);
string ServerFileName = Server.MapPath("~/Images/Folder1/" + FileName);
if (System.IO.File.Exists(ServerFileName) == false) {
FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully";
} else {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File : " + FileName.ToString() + " already exsist";
}
}
}
} else {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select a file to upload";
}