2016-12-14 28 views
1

單擊該按鈕並在第一次執行代碼時,button1_Click事件(將PDF複製到新位置)可以很好地工作;第二個按鈕上的C#System.UnathorizedAccessException單擊

然而,當點擊該按鈕第二次(與同一文本框內輸入),它引發以下錯誤:

System.UnauthorizedAuthorizedAccessException: Access to the path "\share\drive....

很顯然,我不希望這是能夠在一個執行兩次會話,給出相同的文本框條目。在我解決這個問題之前,我想解決這個異常錯誤。我錯誤地將路徑打開了嗎?

代碼更新,以顯示解決方案:

public static string Case_No; 

namespace CEB_Process 
{ 
    public partial class Form1 : Form 
    { 

    public Form1() 
    { 
     InitializeComponent(); 
    } 



    //=============================== 
    // TEXT BOX ENTRY 
    //=============================== 
    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     Form1.Case_No = textBox1.Text; 
    } 


    //============================== 
    // CHECK if Direcotry Exists 
    //============================== 

    public void CreateIfMissing(string path) 
    { 
     if (!Directory.Exists(path)) 
     { 
      DirectoryInfo di = Directory.CreateDirectory(path); 
      //Added 
      var permissions = new DirectoryInfo(path); 
      permissions.Attributes &= ~FileAttributes.ReadOnly; 
      MessageBox.Show("The directory was created successfully"); 
     } 
    } 


    //================================= 
    // MOVE Violation PDF's Button Click 
    //================================== 
    private void button1_Click(object sender, EventArgs e) 
    { 

     //Declare Source path directory from text box entry 
     string sourcePath = string.Format(@"\\share\drive\etc{0}", Case_No); 
     string targetPath = string.Format(@"\\share\drive\etc{0}", Case_No);   

      try 
      { 
       //Call Method to Check/Create Path 
       CreateIfMissing(targetPath); 

       //Get TRAKiT Violation PDF's from source 
       foreach (var sourceFilePath in Directory.GetFiles(sourcePath, "*.pdf")) 
       { 
        string fileName = Path.GetFileName(sourceFilePath); 
        string destinationFilePath = Path.Combine(targetPath, fileName); 
        System.IO.File.Copy(sourceFilePath, destinationFilePath, true); 
        File.SetAttributes(destinationFilePath, FileAttributes.Normal); 
       }//End For Each Loop 
       MessageBox.Show("Files Copied Successfully!"); 
      }//end try 
      catch (Exception x) 
      { 
       MessageBox.Show("The process failed", x.ToString()); 
      } 


    }//End Button Module 

}//End Namespace 
}//End Class 
+1

與您的問題無關:'finally {} //與嘗試釋放資源一起使用':一個空的finally塊會做......沒事! (沒有釋放任何資源,不是你需要在這裏...最後只是刪除這個) –

+0

我認爲它是釋放資源。謝謝。 – Tennis

回答

0

我也有這個問題我之前和之後進行復制/刪除添加下面的代碼行。

File.Copy(file, dest, true); 
File.SetAttributes(dest, FileAttributes.Normal); 

(PS:從Why is access to the path denied?兩者)​​

+0

在目錄創建方法中,像魅力一樣工作:'permissions.Attributes&=〜FileAttributes.ReadOnly;'。謝謝! – Tennis

0

我想你使用File.Copy不覆蓋選定的文件。 這意味着該文件正在被複制,並且被操作系統暫時鎖定,然後它不打開修改(只讀)。這是您的UnauthorizedAccessException的原因。

檢查您是否可以首先訪問文件。

+0

進行上述更改後,顯示文件現在可以修改(覆蓋)。 – Tennis

相關問題