Skip to main content
 首页 » 编程设计

c#之WPF:使用匿名方法的 UnauthorizedAccessException

2024年02月23日15zengkefu

事情是这样的,我想创建一个简单的应用程序,从一个站点复制许多文件,然后将它们移动到另一个站点;但使用异步方法并创建一个新线程。

private void button3_Click(object sender, RoutedEventArgs e) 
{ 
 
    //progressBar1.Maximum = _FileInfoArray.Count; 
 
    DispatcherTimer dt1 = new DispatcherTimer(); 
    foreach (FileInfo Fi in _FileInfoArray) 
    { 
        Thread t = new Thread(new ThreadStart(delegate() 
        { 
            DispatcherOperation _dispOp = progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(delegate() 
            { 
 
                File.Copy(txtdestino.Text, Fi.FullName, true); 
 
                //progressBar1.Value = n; 
                //txtstatus.Content = ("Copiados " + n.ToString() + " archivos"); 
                //Thread.Sleep(100); 
            } 
            )); 
            _dispOp.Completed += new EventHandler(_dispOp_Completed); 
        } 
            )); 
        t.Start(); 
    } 
} 

UnauthorizedAccessException 被抛出!它说我无法访问 txtdestino 内容。一些线索?

-------------------------------------------- ------------------------------编辑 这是包含所有更改的版本,得到相同的错误 :( 任何线索?

private void button4_Click(object sender, RoutedEventArgs e) 
{ 
    //First: Build mynames 
    List<string> mynames = new List<string>(); 
    foreach (FileInfo fi in _FileInfoArray) 
    { 
        mynames.Add(fi.FullName); 
    } 
 
 
 
    Thread t = new Thread(new ThreadStart(delegate() 
       { 
          foreach (string fullname in mynames) 
            { 
            DispatcherOperation _dispOp = progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(delegate() 
            { 
                string destino = System.IO.Path.Combine(@"C:\", System.IO.Path.GetFileName(fullname)); 
                File.Copy(fullname, destino, true); 
                //Some progressbar changes 
            } 
            )); 
            _dispOp.Completed += new EventHandler(_dispOp_Completed); 
          } 
        } 
                )); 
        t.Start(); 
    } 

File.Copy(txtdestino.Text, Fi.FullName, true);//这里抛出异常

请您参考如下方法:

对 UI 元素的调用必须在 UI 线程中完成。尝试在循环之前获取文本值。

string txt = txtdestino.Text; 
foreach (FileInfo Fi in _FileInfoArray) 
{ 
    .... 
    File.Copy(txt, Fi.FullName, true);