【问题标题】:C# : saving screenshot into a sub directory within the app base directory?C#:将屏幕截图保存到应用程序基目录中的子目录中?
【发布时间】:2019-11-25 02:21:33
【问题描述】:

我正在尝试将屏幕截图保存到位于应用程序基目录内的img 子目录中;但是,图像文件保存在应用程序基目录中。怎么把图片保存到img子目录下?

代码:

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

【问题讨论】:

  • 你想:System.IO.Path.GetDirectoryName(Application.ExecutablePath);看stackoverflow.com/questions/15653921/get-current-folder-path
  • 您将日期字符串附加到路径的末尾使img 成为文件名的一部分。你需要使用string fileName = Path.Combine(pathString, DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".png"); 之类的东西。或者干脆去掉pathString,直接使用Path.Combine(appDir, "img", DateTime.Now....)
  • 如果您的 img 目录不存在,您可能需要先创建 if 再保存,另外,您应该执行 fileName = Path.Combine(pathString, $"{DateTime.Now.ToString("yyyyMMdd_hhmmss")}.png");,因为您的第一个 Path.Combine 将返回 pathString没有前导反斜杠,在这种情况下,您只需将其保存到基目录中名为 img{DateTime.Now}.png 的文件中。

标签: c# directory screenshot


【解决方案1】:

您只是没有正确组合路径组件和文件名。试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多