Search code examples
c#directoryscreenshot

C# : saving screenshot into a sub directory within the app base directory?


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

Solution

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