Get Path in asp.net for c# - c#

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.

Related

Saving generated images on IIS virtual directory?

I need to create web API that generate some images and return their paths.
I create the path to save using:
var resultPath = "Images/" + obiektId.ToString() + ".png";
var fullPath = HttpContext.Current.Server.MapPath("/" + resultPath);
and return resultPath.
The problem is, that the virtual directory where I keep my site is C:\\sites\siteA and HttpContext.Current.Server.MapPath("/" + resultPath) returns C:\\inetpub\wwwroot\Images\123456.png. Then it is impossible for me to load the image from 10.0.0.106/siteA/Images/123456.png.
How can I save my image in my base virtual directory instead of saving it in wwwroot directory?
string resultPath = obiektId.ToString() + ".png";
string fullPath = System.Web.HttpContext.Current.Server.MapPath("~/Images"+ resultPath );

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?

how to display image using imageurl in C#

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;
}

saveFileDialog create new folder and save inside it

i wanna create backup data in my application I used saveFileDialog, so i can place backup file anywhere i want (Dekstop, drive D, etc)
my backup file will be db, image, video so i guess it's will be easier to place that in one folder let say it's "myBackup" folder (generate automatically with C#)
so if user wanna save in Dekstop all of backup data will be in ~C:\Users\Maju\Desktop\myBackup~
i already successfully generate folder but my file won't save inside that
mySaveFileDialog.FileName = "Backup Database " + dateTimeNow;
if (mySaveFileDialog.ShowDialog() == DialogResult.OK)
{
string fileAsal = System.IO.Path.Combine(Global.myDatabaseLocation, "data.mdb");
FileInfo fi = new FileInfo(mySaveFileDialog.FileName);
string nameFolder = "myBackup";
System.IO.Directory.CreateDirectory(#fi.DirectoryName + "\\" + nameFolder);
string path = System.IO.Path.Combine (fi.DirectoryName, "\\" + nameFolder);
string pathDestination = System.IO.Path.Combine(path, mySaveFileDialog.FileName);
System.IO.File.Copy(fileAsal, pathDestination, true);
}
Is not it easier to use FolderBrowserDialog?
mySaveFileDialog.FileName already includes the path to the file so you need to write
string pathDestination = System.IO.Path.Combine(path, System.IO.Path.GetFileName(mySaveFileDialog.FileName));

Asp.net finding and downloading file

I have File Upload form which users use to upload certain files on the server. The files are uploaded in path that look like this.
"G:\\VS\\Ticketing System2\\UploadedFiles\\" + ProjectId + "\\" + ticketId + "\\TicketFiles\\";
After that I have a repeater which displays some data and have a hyperlink. I want to name the hyperlink"Download files(" + fileCount + ")" and onclicked it should display a regular Save As window. Can you give me some code to do that. I've never done something like this.
To get the number of files in the directory, you need to use IO. Then
string path = #"G:\\VS\\Ticketing System2\\UploadedFiles\\" + ProjectId + "\\" + ticketId + "\\TicketFiles\\";
int numFiles = Directory.GetFiles(path).Length;
Then in your page_load, just change to .Text of the link to include the numFiles variable

Categories

Resources