Saving generated images on IIS virtual directory? - c#

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

Related

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?

File.Create is creating a folder instand of file

I'm writing a function which is going to serialize class and save it to file, some classes must be saved in a different folder. I'm using Unity and C#. Here's my code:
public void save<T>(T data, string fileName) where T : class{
if (fileName == "")
Debug.Log ("Empty file path");
FileStream file = null;
try{
if(fileName.IndexOf("/") > 0){
string[] strDirName = fileName.Split(new char[] {'/'});
string dirName = strDirName[0];
if(!Directory.Exists(Application.persistentDataPath + dirName)){
Directory.CreateDirectory(Application.persistentDataPath + "/" + dirName);
}
}
file = File.Create(constructFilePath(fileName));
string a = constructFilePath(fileName);
binFormatter.Serialize(file, data);
Debug.Log ("File saved succesfully" + fileName);
}catch(IOException e){
Debug.Log(e.ToString());
}finally{
if(file != null)
file.Close();
}
}
string constructFilePath(string fileName){
return Path.Combine(Application.persistentDataPath, fileName);
}
I have no idea why it's saving files as folder, this happens since I added this line to construct constructFilePath
if(fileName[0] != "/")
fileName = "/" + fileName;
But without this file it's creating different folder. It's concatenating the Application.persistentDataPath with the folder name and creates the file there
so if my persistentDataPath = C:/Users/User/AppData/LocalLow/DefaultCompany/TestGame and I want to store the file inside this folder in folder a and store file b in it
C:/Users/User/AppData/LocalLow/DefaultCompany/TestGame/a/b
it creates folder with name TestGamea and stores b inside it
C:/Users/User/AppData/LocalLow/DefaultCompany/TestGamea/b
You are evaluating one thing and performing something different here:
if(!Directory.Exists(Application.persistentDataPath + dirName)){
Directory.CreateDirectory(Application.persistentDataPath + "/" + dirName);
}
Change this to:
if(!Directory.Exists(Path.Combine(Application.persistentDataPath, dirName))){
Directory.CreateDirectory(Path.Combine(Application.persistentDataPath, dirName));
}
Like Eric said, use Path.Combine. it will reliably combine path parts and ensure you get the same result every time so you don't have to worry about string manipulation.

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

C# Automatically Detecting the computer name/ file path

I am making a program to distribute to people. Currently I'm using:
bitmap.Save("C:/My OVMK Photos//OpenVMK" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg", ImageFormat.Jpeg);
I want to make it to auto detect their computer file path to desktop so it will save to the folder on the desktop.
I'm looking to use This code:
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
filePath =filePath +#"\Error Log\";
string extension = ".log";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
How would I implement that?
I'm assuming that it's not working for some reason. You need to:
Make sure that you already have an "Error Log" folder on the desktop
Use Path.Combine to combine filepath with "Error Log", rather than concatenation
You have everything in place. Just save the bitmap to the filePath that you created instead of
"C:/My OVMK Photos//OpenVMK"
bitmap.Save(filePath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg", ImageFormat.Jpeg);
Use a function like this
void SaveToDesktop(Bitmap bitmap)
{
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
filepath = Path.Combine(filePath,"Error Log");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
filepath = Path.Combine(filepath, DateTime.Now.ToString("image_yyyyMMddHHmmss") + ".jpg");
bitmap.Save(filepath, ImageFormat.Jpeg);
}
then instead of using bitmap.Save
do SaveToDesktop(bitmap);

Get Path in asp.net for 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.

Categories

Resources