單擊該按鈕並在第一次執行代碼時,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
與您的問題無關:'finally {} //與嘗試釋放資源一起使用':一個空的finally塊會做......沒事! (沒有釋放任何資源,不是你需要在這裏...最後只是刪除這個) –
我認爲它是釋放資源。謝謝。 – Tennis