views:

133

answers:

1

I'm trying to save a picture in a relative path of my project. I want it to be in a folder called "images". By using this code

theImage.Save("\\images\\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

I realized by testing with an absolute path, that the folder "images" must exist for it to work. problem is, I don't know what the root folder for the project is, so I can manually create the folder in windows explorer. how can I fix my problem?

A: 

Directory.Create("images");
theImage.Save(@"images\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

Directory.Create will only make a folder if one does not yet exist, so no need to worry about that. The @ before a string literal makes it so that the only character that needs to be escaped is the " which is done like "". Anyways, I don't think you should have to make your own folder manually now. Also, for future reference, you can get the current working directory programmatically by using Environment.CurrentDirectory.

EDIT: In that case, try:
Directory.CreateDirectory("images");
string path = Path.Combine(Environment.CurrentDirectory, @"images\image.jpg"; theImage.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

Brett Widmeier
hmmmm weird, the directory gets created, but the file doesn't save. i mean, the directory stays empty...note: it's Directory.CreateDirectory. and you need the system.io
jello
somehow, when I specify an absolute path, everything's fine. but as soon as it's relative, it doesn't save...
jello
editing with new suggestion
Brett Widmeier
Would it work if you prepended the the path with .\ ?
Nick
@Nick - That should also work. I prefer Environment.CurrentDirectory, but I guess that is just personal preference.
Brett Widmeier
This is minor, but I think Environment.CurrentDirectory can misbehave if you are running as a service. Not 100% sure on that, but I think it returns the dir of the SCM, and not the service exe itself. Not sure if .\ would behave better though. Sometimes GetType().GetExecutingAssembly() is your best option.
Nick
still doesn't work....
jello
nick, what is GetType().GetExecutingAssembly()? cause VS tells me that GetExecutingAssembly() doesn't exist
jello