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?
Related
I have developed a web application in asp.net c# , I want to upload a file from client machine to server.I have used to the following code
string path = Convert.ToString(ConfigurationManager.AppSettings["DocumentPath"]);
FileUpload1.SaveAs(Server.MapPath(path) + FileUpload1.FileName);
Try:
string path = Convert.ToString(ConfigurationManager.AppSettings["DocumentPath"]);
string strImageName3 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + System.IO.Path.GetFileName(FileUpload1.FileName);
string strFilePath3 = Server.MapPath(path);
FileUpload1.SaveAs(strFilePath3 + strImageName3);
this DateTime.Now.ToString("yyyyMMddHHmmssfff") for adding yyyyMMddHHmmssfff string to the uploaded file name for unique uploaded filename.
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);
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//string path = Server.MapPath(#"~\\"+Session["parentfolder"].ToString() +"\\"+ Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName);
string root = Server.MapPath("~");
string path = Path.GetDirectoryName(root);
string path1 = Path.GetDirectoryName(path);
string rootfolder = Path.GetDirectoryName(path1);
string imagepath = rootfolder + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
FileUpload1.SaveAs(imagepath);
//objBAL.SaveImage("Image", Session["brandname"].ToString(), Seasonfolders.SelectedItem.Text, stylefolders.SelectedItem.Text, FileName, imagepath, Convert.ToInt32(Session["Empcode"]));
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
}
uploadedimage is ID for Image control. The path of imagepath is E:\Folder1\Folder2\Folder3\Images\1.png
The image is getting saved but I cannot able to display the uploaded image. Do I need to add anything in this line which is to display an image ..
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
Hosting websites or stuff on iis, does not work this way. There are a few concepts one needs to learn on that front, but the best place to start with is understand what is virtual directory.
One quote from the this page:
In IIS 7, each application must have a virtual directory, known as the
root virtual directory, and maps the application to the physical
directory that contains the application's content
So it means this is a directory where the application's "content" reside; it could be simple text files, images, etc, to complex server side pages like aspx or even classic asp, or php, etc. Now anything out of this directory is not accessible by the hosted web application.
Hence the path you intend to share doesn't work that way. There are a few options to handle this scenario.
In iis you could create a sub-virtual directory, and map its path to where your images are stored to the physical location where the images reside.
Provided your web application (when hosted on iis) has access to the path where the images reside, you can write code to read the file, and send the stream of bytes back so that your web page can render image properly.
2nd approach is usually implemented by a handler (ashx) via which you can pass the image name as query string argument, and return the bytes. Hence in short you do something like this:
uploadedImage.ImageUrl = "~/MyImageHandler.ashx?filename=foo.png" //in ur server code.
In the handler you write something like this:
public class MyImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
context.Response.ContentType = "image/png";
var filepath = #"E:\your_image_dir\" + Request.QueryString["filename"];
//Ensure you have permissions else the below line will throw exception.
context.Response.WriteFile(filepath);
}
public bool IsReusable {
get {
return false;
}
}
}
The image Url in your image should be like this
"~/"+ imagepath
Try removing Server.MapPath
Try this
Create Data Folder in your root directory
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string imagepath =Server.MapPath("~/Data/"+FileName);
FileUpload1.SaveAs(imagepath);
uploadedimage.ImageUrl="~/"+imagepath;
}
I am making a website having image upload module.In my localhost server its working perfectly. That means i can upload images and save it. But when i host my solution i am getting a error. That is, Access to the path is denied.
This is the code i have used...
string fileName = FileUpload1.FileName.ToString();
string uploadFolderPath = "~/up_foto/";
string filePath = HttpContext.Current.Server.MapPath(uploadFolderPath);
FileUpload1.SaveAs(filePath + "\\" + fileName);`
What the wrong in this.. Please help me....
Thanks in advance....
I am afraid there's nothing wrong with your code, if it runs locally. Instead, you have to make sure if on the host environment the user "IUSER", or "IIS_IUSER", or the like, has access (Read/Write) to the upload folder.
Since you are getting "Access to the path is denied", Did you check the folder you are trying to upload is having write access
you can use Path.combine or server.mappath (dont forget to add System.IO in the namespaces)
string fileName = FileUpload1.FileName.ToString();
string uploadFolderPath = "~/Uploads/Images/";
string filePath1 = Server.MapPath(uploadFolderPath + fileName);
or
string fileName = FileUpload1.FileName.ToString();
string uploadFolderPath = "~/Uploads/Images/";
string filePath = Server.MapPath(uploadFolderPath);
string filePath1= Path.Combine(filepath1 + fileName);
I am trying to get a path for a file which a users uploads but the path that I am getting is wrong because the path should be for an example
"C:\\Users\\Tranga.Patel\\Downloads\template.xlsx"
but on my program I get
"c:\\windows\\system32\\inetsrv\\Template Final.xlsx"
the code that I am using is
fileName = Path.GetFullPath(fileUpload.PostedFile.FileName);
I also tried using
fileName = Server.MapPath(Path.GetFullPath(fileUpload.PostedFile.FileName));
this give the directory of the project
try using following:
var path=Server.MapPath('Uploads folder path from root directory');
This gives you the folder path from the root directory of your website.
EDIT:- You should be knowing to which path users are saving the file if it is not in your site directory tree.
Are you using a File Upload control? If you are, you just need them to select the document they want to upload and then specify the path you want to save it at. For example
// Get File Name
documentName = Path.GetFileName(fuContentDocuments.FileName);
// Specify your server path
string serverPath = Server.MapPath("../../" + WebConfigurationManager.AppSettings["FilePath"].ToString());
// The final path
string fileLocation = (serverPath + "\\" + userId + "\\" + documentName);
// if folder doesn't exist then create it
if (!Directory.Exists(serverPath + "\\" + userId + "\\"))
{
// create the folder for the file
Directory.CreateDirectory(serverPath + "\\" + userId + "\\");
}
// Upload the file
fuContentDocuments.SaveAs(fileLocation);
Note: UserId is just the users login userId. This way other users wont override it.