2017-03-23 68 views
0

我想用C#多個文件上傳到谷歌驅動打開文件對話框結果正在被另一個進程使用

這是我的上傳按鈕功能

private void bt_upload_Click(object sender, EventArgs e) 
    { 
     Filedialog_init(); 


     DialogResult check_upload = MessageBox.Show("Want to upload these files ?", "Upload", MessageBoxButtons.OKCancel); 

     if (check_upload == DialogResult.OK) 
     { 
      for (int i = 0; i < result.Count; i++) 
      { 
       UploadFilesDrive(service, result[i], filePath[i], Datatype[i]); 
       tx_state.AppendText(result[i] + "Upload Done"); 
      } 
     } 
    } 

這是我Filedialog_init功能

private static void Filedialog_init() 
    { 
     Stream myStream = null; 
     OpenFileDialog openFileDialog = new OpenFileDialog(); 

     openFileDialog.InitialDirectory = "c:\\"; 
     openFileDialog.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*"; 
     openFileDialog.FilterIndex = 1; 
     openFileDialog.RestoreDirectory = true; 
     openFileDialog.Multiselect = false; 

     if (openFileDialog.ShowDialog() == DialogResult.OK) 
     { 
      string filename = null; 
      string _datatype = null; 
      try 
      { 
       if ((myStream = openFileDialog.OpenFile()) != null) 
       { 
        foreach (String file in openFileDialog.FileNames) 
        { 
         filename = Path.GetFileName(file); 
         result.Add(filename); 
         // only show the name of file 

         Datatype.Add(_datatype); 
        } 
        filePath = openFileDialog.FileNames; 
        Datatype.ForEach(Console.WriteLine); 
       } 

       openFileDialog.Dispose(); 


      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); 
      } 
     } 
     else 
      MessageBox.Show("Upload Cancel"); 
    } 

我可以通過指定文件名及其數據類型和路徑直接上傳文件

但是,當我使用openfiledialog,它出錯了「我的文件正在被另一個進程使用」

我該如何解決這個問題?

+0

哪裏是這將打開文件對話框,並給出了選擇文件的代碼。因爲在那個代碼中你正在鎖定文件訪問。 –

+0

我試圖使用opfiledialog.Dispose(),但它沒有工作 –

+0

此行'(myStream = openFileDialog.OpenFile()'仍然保持鎖定文件。嘗試使用流與'使用',以便它將處置流,以及鎖,而不是像使用(流myStream = openFileDialog.OpenFile()){您的代碼在這裏...} –

回答

0

問題在於你的代碼在這裏,

(myStream = openFileDialog.OpenFile())這條線是保持在文件鎖定,因爲你的myStream沒有得到disposed。只要完成了它,您就需要dispose流。

因此,儘可能使用using,因爲它會盡快dispose流使用行結束執行。有關using的更多詳細信息。

你可以嘗試如下,

using(Stream myStream = openFileDialog.OpenFile()) 
{ 
    //Your code here... 
} 
+0

謝謝!它的工作!我已經吸取教訓 –

+0

如果這解決了您的問題,請接受這個答案如此問題被關閉。 –

相關問題