【发布时间】: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