Exporting to Outlook (.ics file) from a .NET web application - c#

Basically I'm trying to create and export a .ics file from a C# web application so the user can save it, and open it in Outlook to add something to their calendar.
Here's the code I have at the moment...
string icsFile = createICSFile(description, startDate, endDate, summary);
//Get the paths required for writing the file to a temp destination on
//the server. In the directory where the application runs from.
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
string assPath = Path.GetDirectoryName(path).ToString();
string fileName = emplNo + "App.ics";
string fullPath = assPath.Substring(0, assPath.Length-4);
fullPath = fullPath + #"\VTData\Calendar_Event\UserICSFiles";
string writePath = fullPath + #"\" + fileName; //writepath is the path to the file itself.
//If the file already exists, delete it so a new one can be written.
if (File.Exists(writePath))
{
File.Delete(writePath);
}
//Write the file.
using (System.IO.StreamWriter file = new System.IO.StreamWriter( writePath, true))
{
file.WriteLine(icsFile);
}
The above works perfectly. It writes the file and deletes any old ones first.
My main issue is how to get it to the user?
I tried redirecting the page straight to the path of the file:
Response.Redirect(writePath);
It does not work, and throws the following error:
htmlfile: Access is denied.
NOTE: If I copy and paste the contents of writePath, and paste it into Internet Explorer, a save file dialog box opens and allows me to download the .ics file.
I also tried to prompt a save dialog box to download the file,
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "inline; filename=" + fileName + ";");
response.TransmitFile(fullPath);
response.Flush(); // Error happens here
response.End();
It does not work either.
Access to the path 'C:\VT\VT-WEB MCSC\*some of path omitted *\VTData\Calendar_Event\UserICSFiles' is denied.
Access denied error again.
What may be the problem?

It sounds like you are trying to give the user the physical path to the file instead of the virtual path. Try changing the path so it ends up in the www.yoursite.com/date.ics format instead. This will allow your users to download it. The issue is that they don't have access to the C drive on your server.
Here is a link to how to do this:
http://www.west-wind.com/weblog/posts/2007/May/21/Downloading-a-File-with-a-Save-As-Dialog-in-ASPNET
Basically, you need the following line in your code:
Response.TransmitFile( Server.MapPath("~/VTData/Calendar_Event/UserICSFiles/App.ics") );
Use this instead of the Response.Redirect(writePath); and you should be good to go.

Related

C# Download File from a network drive

I have a file that is located at a network drive. The user access is already created to have full access to the path. But it seems that when I ran the following code to get the file, the browser just does not respond.
FileInfo file = new FileInfo(GetDocumentUploadFolder(ID) + fileName);
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
this.Page.Response.ClearContent();
// Clear the header of the response
this.Page.Response.ClearHeaders();
// Set the ContentType
this.Page.Response.ContentType = "application/pdf";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
this.Page.Response.WriteFile(file.FullName);
// End the response
this.Page.Response.End();
}
I tried using this.Page.Response.TransmitFile(file.FullName); and it also does not work. The page seems to stop functioning after this.Page.Response.End();
Any ideas?
No matter where file a stored. Your action must return a file as the result:
public FileResult GetBytes()
{
string path = Server.MapPath("~/Files/PDFIcon.pdf");
byte[] mas = System.IO.File.ReadAllBytes(path);
string file_type = "application/pdf";
string file_name = "PDFIcon.pdf";
return File(mas, file_type, file_name);
}
Server.MapPath(filePath string) - must have access to the file.
I am able to do a workaround by copying the files first from the network drive to local path and then do a TransmitFile from there:
FileInfo file = new FileInfo(GetDocumentUploadFolder(ID) + fileName);
string strFolder = Server.MapPath(LocalLocation);
string strDestination = Server.MapPath(LocalLocation + "\\" + fileName);
// Checking if file exists
if (file.Exists)
{
if (!Directory.Exists(strFolder))
Directory.CreateDirectory(strFolder);
// Delete contents in this folder
Common.DeleteFiles(strFolder, "*.*");
file.CopyTo(strDestination, true);
// Clear the content of the response
this.Page.Response.ClearContent();
// Clear the header of the response
this.Page.Response.ClearHeaders();
// Set the ContentType
this.Page.Response.ContentType = "application/pdf";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
this.Page.Response.TransmitFile(strDestination);
// End the response
this.Page.Response.End();
}

Uploading files from a network share

I am trying copy a file from a network share (drive letter\folder) to a SharePoint document library using asp.net (C#) when I run the code locally and select a drive letter to copy from everything works fine, but when I publish it to IIS I get an error - Could not find a part of the path 'L:\Test\Test.Doc'. I am guessing this is because the drive mapping doesn't exist from IIS.
The code to get the file is:
if (FileUpload1.HasFile)
{
string spSite = System.Configuration.ConfigurationManager.AppSettings["SharePointSite"];
string RelativePath = System.Configuration.ConfigurationManager.AppSettings["DocumentLibraryRelativePath"];
SharePointIntegration sp = new SharePointIntegration();
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
string filePath = Path.GetDirectoryName(FileUpload1.PostedFile.FileName) + "\\" + fileName + fileExtension;
sp.UploadDocument(spSite, RelativePath, "Documents", filePath, fileName, recordID.ToString(), (string)HttpContext.Current.Session["UserName"], fileExtension);
GetAttachments();
}
I am using the SaveBinaryDirect method to save the file in SharePoint - sp.UploadDocument(spSite, RelativePath, .......).
What do I need to change to get the file when it is running on IIS?

to download a page as pdf file and save in a local folder in C#

protected void btn_download_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
string filePath = Server.MapPath(Request.ApplicationPath) + " \\Member\\Attachments" ;
Response.TransmitFile(filePath);
Response.End();
}
I used the above link code to download a webpage to a pdf file and save in a local file. But i am getting the error as access to the path is denied. Please help me out.
Missing local file name in filePath variable. Append file name to it. And make sure that you attachment directory have permission to access files for IIS users.
string filePath = Server.MapPath(Request.ApplicationPath) + " \\Member\\Attachments\\foo.pdf" ; \\Append your file name here.

How to create and save a temporary file on Microsoft Azure virtual server

I am using a free MS Azure virtual webserver for my site.
On my dev machine I can successfully create a CSV file, save it to a relative temp directory, and then download it to the browser client.
However, when I run it from the Azure site, I get the following error:
System.IO.DirectoryNotFoundException: Could not find a part of the
path 'D:\home\site\wwwroot\temp\somefile.csv'.
Does the free version of Azure Websites block us from saving files to disk? If not, where are we allowed to create/save files that we generate on the fly?
Code Example
private FilePathResult SaveVolunteersToCsvFile(List<Volunteer> volunteers)
{
string virtualPathToDirectory = "~/temp";
string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
string fileName = "Volunteers.csv";
string pathToFile = Path.Combine(physicalPathToDirectory, fileName);
StringBuilder sb = new StringBuilder();
// Column Headers
sb.AppendLine("First Name,Last Name,Phone,Email,Approved,Has Background Check");
// CSV Rows
foreach (var volunteer in volunteers)
{
sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5},{6}",
volunteer.FirstName, volunteer.LastName, volunteer.MobilePhone.FormatPhoneNumber(), volunteer.EmailAddress, volunteer.IsApproved, volunteer.HasBackgroundCheckOnFile));
}
using (StreamWriter outfile = new StreamWriter(pathToFile))
{
outfile.Write(sb.ToString());
}
return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
}
Make sure that the ~/temp folder gets published to the server, as it's possible your publish process isn't including it.
Azure Websites provide environment variables that you can use to get to things like a temporary storage folder. For example, there is a "TEMP" variable you could access to get a path to the TEMP folder specific to your Website.
Change line 2 in your method to this:
//string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
string physicalPathToDirectory = Environment.GetEnvironmentVariable("TEMP");
Then change the last line to this:
//return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
return File(pathToFile, "text/csv", fileName);

How to download a file in IIS?

I have written two methods such as FileUpLoad() and FileDownLoad() to Upload and Download a single file in my local system.
void FileUpLoad()
{
string hfBrowsePath = fuplGridDocs.PostedFile.FileName; //fuplGridDocs is a fileupload control
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = Path.Combine(#"E:\Documents\");
FileInfo FP = new FileInfo(hfBrowsePath);
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value; //hfFileNameAutoGen is a hidden field
fuplGridDocs.PostedFile.SaveAs(destfile);
}
}
void FileDownLoad(LinkButton lnkFileName)
{
string filename = lnkFileName.Text;
string FilePath = Path.Combine(#"E:\Documents", filename);
fuplGridDocs.SaveAs(FilePath);
FileInfo fileToDownLoad = new FileInfo(FilePath);
if (fileToDownLoad.Exists)
{
Process.Start(fileToDownLoad.FullName);
}
else
{
lblMessage.Text = "File Not Saved!";
return;
}
}
While running the application before hosting it in IIS, I can upload a file to the desired location and can also retrieve a file from the saved location. But after publishing it in the localhost, I can only Upload a file. I could not download the saved file. There is no exception too. The Uploaded file is saved in the desired location. I don't know why it is not retrieving the file? Why I cant download the file in IIS? I have searched a lot in the internet, but couldn't find the solution. How to solve this? I am using Windows XP and IIS 5.1 version.
How do you expect your Web Application to do a Process.Start when you deploy this site to a server, your just going to be opening pictures on the server, not on the client PC.
I think this will answer your question: http://www.codeproject.com/Articles/74654/File-Download-in-ASP-NET-and-Tracking-the-Status-o
Also the download file is missing a slash after E:\Documents
another option is to add your wildcard to IIS MIME types

Categories

Resources