2017-07-02 25 views
-2

我想將圖像保存在特定位置。繞過「確認另存爲,是否要替換它」彈出。SaveFileDialog選擇圖像後保存文件(雙擊)

 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

你是什麼意思將路徑保存圖像?你想將它保存到一個文件夾或文件? – Lloyd

+0

我想保存它的文件夾。路徑是我聲明的目錄 – Vincent

+0

那麼爲什麼你使用'SaveFileDialog'而不是'FolderBrowserDialog'? – Lloyd

回答

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."); 
    } 
} 
+0

如果我選擇的圖像是在「桌面」,選擇它後會自動保存/編程到「我的文檔」文件夾 – Vincent

+1

我不確定你的問題是什麼?我以爲你是從'pictureBox1'保存圖像,不是嗎? 'BrowseFolderDialog將允許你選擇保存到哪裏。 –

+0

picturebox1只是一個點擊控件(它也可以是一個按鈕)。最好的例子是「Facebook個人資料照片上傳」。或「請上傳照片」功能。 – Vincent