0

I am attempting to save a screenshot into the img sub-directory located inside of the apps base directory; however, the image file is saved within the apps base directory. What should I do to save the image into the img sub-directory?

Code:

private void screenCapture()
{
    try
    {
        string appDir = AppDomain.CurrentDomain.BaseDirectory;
        string pathString = System.IO.Path.Combine(appDir, "img");

        Bitmap memoryImage;
        memoryImage = new Bitmap(1000, 900);
        Size s = new Size(memoryImage.Width, memoryImage.Height);

        Graphics memoryGraphics = Graphics.FromImage(memoryImage);

        memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);

        string fileName =
            string.Format(pathString
            + DateTime.Now.ToString("yyyyMMdd_hhmmss")
            + ".png");

        // save it  
        memoryImage.Save(fileName);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dottedquad
  • 1,371
  • 6
  • 24
  • 55
  • Do you want to: System.IO.Path.GetDirectoryName(Application.ExecutablePath); Look at https://stackoverflow.com/questions/15653921/get-current-folder-path – Prateek Shrivastava Nov 25 '19 at 02:25
  • 1
    You're appending the date string to the end of the path _making `img` part of the file name_. You need to use something like `string fileName = Path.Combine(pathString, DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".png");`. Or just get rid of `pathString` and directy use `Path.Combine(appDir, "img", DateTime.Now....)`. – 41686d6564 stands w. Palestine Nov 25 '19 at 02:34
  • 1
    If your `img` directory doesn't exist, you might want to create if first before saving, also, you should do `fileName = Path.Combine(pathString, $"{DateTime.Now.ToString("yyyyMMdd_hhmmss")}.png");`, sins your first `Path.Combine` would return `pathString` with no leading backslash in which case you would just be saving it to a file named `img{DateTime.Now}.png` in the base directory. – Vincent Bree Nov 25 '19 at 02:41

1 Answers1

1

You're just not combining the path components and the filename properly. Try this:

string appDir = AppDomain.CurrentDomain.BaseDirectory;
string pathString = System.IO.Path.Combine(appDir, "img");
string fileName = DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".png";
string fullPath = System.IO.Path.Combine(pathString, fileName);
robbpriestley
  • 3,050
  • 2
  • 24
  • 36