I'm trying to create a folder on the directory where the .exe file is and save a picture in that folder.
Right now that folder doesn't exist so I'd like to be created. Here's the code I have:
public void SavePictureToFileSystem(string path, Image picture)
{
string pictureFolderPath = path + "\\" + ConfigurationManager.AppSettings["picturesFolderPath"].ToString();
picture.Save(pictureFolderPath + "1.jpg");
}
The Image isn't being saved to the pictureFolderPath but to the path variable. What do I need to accomplish this?
Thanks for the help! This is what I ended up with:
public void SavePictureToFileSystem(string path, Image picture)
{
var pictureFolderPath = Path.Combine(path, ConfigurationManager.AppSettings["picturesFolderPath"].ToString());
if (!Directory.Exists(pictureFolderPath))
{
Directory.CreateDirectory(pictureFolderPath);
}
picture.Save(Path.Combine(pictureFolderPath, "1.jpg"));
}
I suspect your problem is that ConfigurationManager.AppSettings["picturesFolderPath"].ToString() returns a folder-path that is empty or, more likely, does not end with a trailing back-slash. This would mean that the final constructed path would end up looking like c:\dir1.jpg rather than c:\dir\1.jpg, which is what I think you really want.
In any case, it's much better to rely onPath.Combinethan to try to deal with the combining logic yourself. It deals with precisely these sorts of corner-cases, plus, as a bonus, it's platform-independent.
var appFolderPath = ConfigurationManager.AppSettings["picturesFolderPath"]
.ToString();
// This part, I copied pretty much verbatim from your sample, expect
// using Path.Combine. The logic does seem a little suspect though..
// Does appFolder path really represent a subdirectory name?
var pictureFolderPath = Path.Combine(path, appFolderPath);
// Create folder if it doesn't exist
Directory.Create(pictureFolderPath);
// Final image path also constructed with Path.Combine
var imagePath = Path.Combine(pictureFolderPath, "1.jpg")
picture.Save(imagePath);
I suspect ConfigurationManager.AppSettings["picturesFolderPath"].ToString() might be empty, so the pictureFolderPath variable is only being set to the path value. Make sure it is set properly and the value is being returned. Put a breakpoint on that line and check it in the Watch/Immediate windows.
You could try to create the directory first:
Directory.CreateDirectory(pictureFolderPath);
Related
I have xml files that contain href file paths to images (e.g. "....\images\image.jpg"). The hrefs contain relative paths. Now, I need to extract the hrefs to the images and turn them into absolute paths in the file system.
I know about the GetFullPath method, but I tried it and it only seems to work from the CurrentDirectory set, which appears to be C: so I don't see how I could use that. And still, I have the absolute path of the file containing the hrefs, and the href relative paths, so since it is a simple task for me to count back the number of "....\" parts based on the absolute path of the containing file, it seems there must be a way to do this programmatically as well.
I'm hoping there's some simple method I just don't know about! Any ideas?
string exactPath = Path.GetFullPath(yourRelativePath);
works
Assuming you know the real directory the XML file lives in use Path.Combine, e.g.
var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");
If you want to get back the full path with any ..'s collapsed then you can use:
Path.GetFullPath((new Uri(absolute_path)).LocalPath);
This worked.
var s = Path.Combine(#"C:\some\location", #"..\other\file.txt");
s = Path.GetFullPath(s);
It`s best way for convert the Relative path to the absolute path!
string absolutePath = System.IO.Path.GetFullPath(relativePath);
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, #"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Have you tried Server.MapPath method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx
I have an MVC project and a class library just for saving and deleting images.
I have the path to those images stored in a variable as a relative path
Content\images\ that I reference inside the Save() and Delete() methods.
The save method works as I would think but the delete throws an error as it's relating the current path from the window directory.
// Works fine
File.WriteAllBytes(Path.Combine(Settings.ImagesPath, filename), binaryData);
// Error saying it cannot find the path in the C:\windows\system32\folder
File.Delete(Path.Combine(Settings.ImagesPath, filename));
I'd like to be able to switch between relative and absolute paths in my Settings.ImagesPath string but every SO article I've tried works for one scenario or the other. What's the best way to convert absolute or relative paths to some common way to deal with them?
You should use Server.MapPath method to generate the path to the location and use that in your Path.Combine method.
var fullPath = Path.Combine(Server.MapPath(Settings.ImagesPath), filename);
System.IO.File.Delete(fullPath);
Server.MapPath method returns the physical file path that corresponds to the specified virtual path. In this case, Server.MapPath(Settings.ImagesPath) will return the physical file path to your Content\images\ which is inside your app root.
You should do the same when you save the file as well.
You can also check the existence of the file before attempting to delete it
var fullPath = Path.Combine(Server.MapPath(Settings.ImagesPath), filename);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
Server.MapPath expects a relative path. So if you have an absolute value in the Settings.ImagePath, You can use the Path.IsPathRooted method to determine if it is a virtual path or not
var p = Path.Combine(Path.IsPathRooted(Settings.ImagesPath)
? path : Server.MapPath(Settings.ImagesPath), name);
if (System.IO.File.Exists(p))
{
System.IO.File.Delete(p);
}
When you use the virutal path, make sure it start with ~.
Settings.ImagesPath = #"~\Contents\Pictures";
I'm creating a logger for my app and I'm stuck with a problem I need to save my log file in my C drive but when I'm executing the Code its give me an error "Given Path Format Is Not Supported" My current code is given below
string path="C:\\Logger\\"+DateTime.Now.Date.ToString()+".txt";
public void CreateDirectory()
{
if(!File.Exists(path))
{
File.Create(path);
}
}
any solutions????
You're going to have to format the date:
string path="C:\\Logger\\"+DateTime.Now.Date.ToString("yyyy_MM_dd")+".txt";
because the operating system isn't going to accept something like this:
C:\Logger\07/27/2013.txt
Now, for future reference, consider using Path.Combine to build your paths:
var path = Path.Combine("C:\\Logger",
DateTime.Now.Date.ToString("yyyy_MM_dd"),
".txt");
You won't have to determine when to provide back slashes and when not to. If there isn't one, it will be appended for you.
Finally, you may experience problems if the directory doesn't exist. Something you can do to mitigate that is this:
var path = ...
var dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
{
Directory.Create(dir);
}
But even then, you can run into permissions issues during runtime.
Check that the result of this: DateTime.Now.Date.ToString() is accepted by the operating system.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting path relative to the current working directory?
I have code in C# that includes some images from an absolute path to a relative so the image can be found no matter where the application fold is located.
For example the path in my code (and in my laptop for the image) is
C:/something/res/images/image1.jpeg
and I want the path in my code to be
..../images/image1.jpeg
So it can run wherever the folder is put, whatever the name of the C: partition is etc.
I want to have a path in my code which is independant of the application folder location or if it is in another partition, as long as it is in the same folder as the the rest of the solution.
I have this code:
try
{
File.Delete("C:/JPD/SCRAT/Desktop/Project/Resources/images/image1.jpeg");
}
catch (Exception)
{
MessageBox.Show("File not found:C:/Users/JPD/Desktop/Project/images/image1.jpeg");
}
This code only runs if the file and folder are in that certain path, (which is also the location of the code) I wish for that path to be relative so wherever I put the whole folder (code, files etc) the program will still work as long as the code (which is under project folder) is at the same location with the folder images... what should I do?
Relative paths are based from the binary file from which your application is running. By default, your binary files will be outputted in the [directory of your .csproj]/bin/debug. So let's say you wanted to create your images folder at the same level as your .csproj. Then you could access your images using the relative path "../../images/someImage.jpg".
To get a better feel for this, try out the following as a test:
1) create a new visual studio sample project,
2) create an images folder at the same level as the .csproj
3) put some files in the images folder
4) put this sample code in your main method -
static void Main(string[] args)
{
Console.WriteLine(Directory.GetCurrentDirectory());
foreach (string s in Directory.EnumerateFiles("../../images/"))
{
Console.WriteLine(s);
}
Console.ReadLine(); // Just to keep the console from disappearing.
}
You should see the relative paths of all the files you placed in step (3).
see: Getting path relative to the current working directory?
Uri uri1 = new Uri(#"c:\foo\bar\blop\blap");
Uri uri2 = new Uri(#"c:\foo\bar\");
string relativePath = uri2.MakeRelativeUri(uri1).ToString();
Depending on the set up of your program, you might be able to simply use a relative path by skipping a part of the full path string. It's not braggable, so J. Skit might be up my shiny for it but I'm getting the impression that you simply want to make it work. Beauty being a later concern.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
String relativePath = absolutePath.Substring(13);
You could then, if you need/wish, exchange the number 13 (which is an ugly and undesirable approach, still working, though) for a dynamically computed one. For instance (assuming that the directory "HereWeStart", where your relative path is starting, is the first occurrence of that string in absolutePath) you could go as follows.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
int relativePathStartIndex = absolutePath.IndexOf("HereWeStart");
String relativePath = absolutePath.Substring(relativePathStartIndex);
Also, your question begs an other question. I'd like to know how you're obtaining the absolute path. Perhaps there's an even more clever way to avoid the hustle all together?
EDIT
You could also try the following approach. Forget the Directory class giving you an absolute path. Go for the relative path straight off. I'm assuming that all the files you're attempting to remove are in the same directory. If not, you'll need to add some more lines but we'll cross that bridge when we get there.
Don't forget to mark an answer as green-checked (or explain what's missing or improvable still).
String
deletableTarget = #"\images\image1.jpeg",
hereWeAre = Environment.CurrentDirectory;
MessageBox.Show("The taget path is:\n" + hereWeAre + deletableTarget);
try
{ File.Delete(hereWeAre + deletableTarget); }
catch (Exception exception)
{ MessageBox.Show(exception.Message); }
Also, please note that I took the liberty of changing your exception handling. While yours is working, it's a better style to rely on the built-in messaging system. That way you'll get more professionally looking error messages. Not that we ever get any errors at run-time, right? ;)
I have xml files that contain href file paths to images (e.g. "....\images\image.jpg"). The hrefs contain relative paths. Now, I need to extract the hrefs to the images and turn them into absolute paths in the file system.
I know about the GetFullPath method, but I tried it and it only seems to work from the CurrentDirectory set, which appears to be C: so I don't see how I could use that. And still, I have the absolute path of the file containing the hrefs, and the href relative paths, so since it is a simple task for me to count back the number of "....\" parts based on the absolute path of the containing file, it seems there must be a way to do this programmatically as well.
I'm hoping there's some simple method I just don't know about! Any ideas?
string exactPath = Path.GetFullPath(yourRelativePath);
works
Assuming you know the real directory the XML file lives in use Path.Combine, e.g.
var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");
If you want to get back the full path with any ..'s collapsed then you can use:
Path.GetFullPath((new Uri(absolute_path)).LocalPath);
This worked.
var s = Path.Combine(#"C:\some\location", #"..\other\file.txt");
s = Path.GetFullPath(s);
It`s best way for convert the Relative path to the absolute path!
string absolutePath = System.IO.Path.GetFullPath(relativePath);
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, #"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Have you tried Server.MapPath method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx