Chamal Fernando回答我的问题,非常感谢,
您可以在不使用文件流的情况下使用fileName。 将“保存文件对话框”的OverwritePrompt属性设置为false。 然后使while循环计算索引。
private void button1_Click(object sender,EventArgs e) { 尝试 { // abre aopçãodesalvar como,para selecionar a pasta
SaveFileDialog saveFileDialog1 = new SaveFileDialog
{
//InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonPictures),
Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif",
Title = "Salvar o arquivo de imagem",
RestoreDirectory = true,
};
saveFileDialog1.OverwritePrompt = false;
saveFileDialog1.ShowDialog();
// se o nome do arquivo não for vazio, abre para salvar
if (saveFileDialog1.FileName != "")
{
int fileCount = 0;
string fullPath = saveFileDialog1.FileName;
string fileNamewithoutExt = Path.GetFileNameWithoutExtension(fullPath);
string dirPath = Path.GetDirectoryName(fullPath);
string ext = Path.GetExtension(fullPath);
string newPath = string.Empty;
while (File.Exists(newPath = Path.Combine(dirPath, fileNamewithoutExt + (fileCount > 0 ? "[" + fileCount + "]" : "") + ext)))
{ fileCount++; }
// Salva a imagem no formato certo
switch (saveFileDialog1.FilterIndex)
{
case 1:
this.pictureBoxScreenshot.Image.Save(newPath,
System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case 2:
this.pictureBoxScreenshot.Image.Save(newPath,
System.Drawing.Imaging.ImageFormat.Bmp);
break;
case 3:
this.pictureBoxScreenshot.Image.Save(newPath,
System.Drawing.Imaging.ImageFormat.Gif);
break;
}
}
}
catch (Exception ex)
{ }
}