我想将图片保存在特定位置。绕过“确认另存为,是否要替换它”弹出窗口。
private void pictureBox1_Click(object sender, EventArgs e)
{
string path = "C:\\MyDocs\\TimeIn&Out\\EmployeesPhoto";
Directory.CreateDirectory(path);
saveFileDialog1.InitialDirectory = (@"C:\");
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.Title = "Select Image";
saveFileDialog1.DefaultExt = ".png";
saveFileDialog1.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
saveFileDialog1.OverwritePrompt = false;
if(saveFileDialog1.ShowDialog()==DialogResult.OK)
{
//path = Path.GetDirectoryName(saveFileDialog1.FileName);
//pictureBox1.Image.Save(path, System.Drawing.Imaging.ImageFormat.Png);
// I tried this 2 but not working
}
}
在目录中选择图像后点击picturebox1 => =>那么它必须将图像保存在“路径”中。但它显示了这个弹出窗口。
答案 0 :(得分:0)
设置属性:
saveFileDialog1.OverwritePrompt = false;
应该阻止覆盖警告。我不知道为什么它不适合你,但你可以使用openFileDialog
代替,然后自己保存文件,如果你愿意:
string path = openFileDialog1.FileName;
if (File.Exists(path)){
File.Delete(path);
}
using (FileStream fs = File.Create(openFileDialog1.FileName)) {
fs.Write(imageFile, 0, info.Length);
}
编辑因此,您实际上希望允许用户选择图像,然后将图像保存到具有特定名称的特定文件夹中。你的代码没有做任何事情。 SaveFileDialog
对话框的目的是保存文件,而不是选择文件。使用OpenFileDialog
允许用户选择图像文件,然后自行保存文件。与上面的代码类似,但逻辑不同:
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = @"c:\" ;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Title = "Select Image";
openFileDialog1.DefaultExt = ".png";
openFileDialog1.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
if(openFileDialog1.ShowDialog() == DialogResult.OK) {
try {
string path = string path = @"C:\MyDocs\TimeIn&Out\EmployeesPhoto" + browseFileDialog1.FileName;
if (File.Exists(path)) {
File.Delete(path);
}
if ((myStream = openFileDialog1.OpenFile()) != null) {
using (myStream) {
using (var fs = File.Create(browseFileDialog1.FileName)) {
myStream.CopyTo(fs);
}
}
}
}
catch (Exception ex) {
MessageBox.Show("Error: Could not read file from disk.");
}
}