错误非静态字段需要对象引用

时间:2014-03-16 21:04:02

标签: c# forms

我正在尝试将我的代码作为新线程运行,现在我遇到错误第59行foreach上的非静态字段,方法或属性'Deploy.Form1.textBox1'需要对象引用(string dirPath在Directory.GetDirectories中(textBox1.Text,“*”

namespace Deploy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            {
                FolderBrowserDialog objFolderDialog = new FolderBrowserDialog();
                textBox1.Text = GetNetworkFolders(objFolderDialog);

                NewThread();
            }
        }

        public static string GetNetworkFolders(FolderBrowserDialog oFolderBrowserDialog)
        {
            Type type = oFolderBrowserDialog.GetType();
            System.Reflection.FieldInfo fieldInfo = type.GetField("rootFolder", BindingFlags.NonPublic | BindingFlags.Instance);
            fieldInfo.SetValue(oFolderBrowserDialog, (Environment.SpecialFolder)18);
            if (oFolderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                return oFolderBrowserDialog.SelectedPath;
            }
            else
            {
                return "";
            }

        }
            static void Main( string[] args )
            {
             Thread t = new Thread( NewThread );
             t.Start();
            }

            static void NewThread()
            {
                foreach (string dirPath in Directory.GetDirectories(textBox1.Text, "*",
                SearchOption.AllDirectories))
                Directory.CreateDirectory(dirPath.Replace(textBox1.Text, textBox2.Text));

                foreach (string newPath in Directory.GetFiles(textBox1.Text, "*.*",
                SearchOption.AllDirectories))
                File.Copy(newPath, newPath.Replace(textBox1.Text, textBox2.Text), true);

        }
    }
}

1 个答案:

答案 0 :(得分:1)

由于DeanOC所说的确切原因,您需要在新线程中尝试访问的文本框控件上使用Invoke方法。请尝试以下方法:

    string  directory = string.Empty;
    textBox1.Invoke((MethodInvoker)delegate {
       directory = textBox1.Text; // runs on UI thread
    });

    string  directory2 = string.Empty;
    textBox2.Invoke((MethodInvoker)delegate {
       directory = textBox2.Text; // runs on UI thread
    });