gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:08 25 4
gpt4 key购买 nike

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

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);

关于c# - WPF:使用匿名方法的 UnauthorizedAccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4655059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com