C# Automatically Detecting the computer name/ file path - c#

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

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

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

File uploading into server

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

How save uploaded file? c# mvc

I want upload an image file to project's folder but I have an error in my catch:
Could not find a part of the path 'C:\project\uploads\logotipos\11111\'.
What am I do wrong? I want save that image uploaded by my client in that folder... that folder exists... ah if I put a breakpoint for folder_exists3 that shows me a true value!
My code is:
try
{
var fileName = dados.cod_cliente;
bool folder_exists = Directory.Exists(Server.MapPath("~/uploads"));
if(!folder_exists)
Directory.CreateDirectory(Server.MapPath("~/uploads"));
bool folder_exists2 = Directory.Exists(Server.MapPath("~/uploads/logo"));
if(!folder_exists2)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo"));
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/"));
}
catch(Exception e)
{
}
Someone knows what I'm do wrong?
Thank you :)
Try this:
string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
string targetPath = Path.Combine(targetFolder, yourFileName);
file.SaveAs(targetPath);
Your error is the following:
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
You check if a directory exists, but you should check if the file exists:
File.Exists(....);
You need filename
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/" + your_image_fillename));
Remove the last part of the path to save you have an extra "/"
It should be
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName);
Also you do not have a file extension set.

Categories

Resources