1

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'm not getting an exception. The problem is the picture is saving to the path variable with the pictureFolderPath string being appended as the pictures Filename. –  Nov 03 '10 at 13:40

3 Answers3

6

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);
Ani
  • 111,048
  • 26
  • 262
  • 307
1

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.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
0

You could try to create the directory first:

Directory.CreateDirectory(pictureFolderPath);
Cpt. eMco
  • 565
  • 4
  • 13