C#将文件路径传递给其他方法

问题描述

如何将从已删除文件获取文件路径传递为另一个函数/方法中的路径?

在C#Windows窗体程序中,我具有可以将文件拖放到其中的列表框,它在该列表框中显示文件路径:

 public Form1()
        {
            InitializeComponent();
            this.listBox1.DragDrop += new
           System.Windows.Forms.DragEventHandler(this.listBox1_DragDrop);
            this.listBox1.dragenter += new
                       System.Windows.Forms.DragEventHandler(this.listBox1_dragenter);
        }
        // drag and drop process
        private void listBox1_dragenter(object sender,System.Windows.Forms.DragEventArgs e)
        {
            var files = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (files.Length == 1 && listBox1.Items.Count == 0)
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
        private void listBox1_DragDrop(object sender,System.Windows.Forms.DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop,false);
            int i;
            for (i = 0; i < s.Length; i++)
                listBox1.Items.Add(s[i]);
        }

在程序的另一部分中,按一下按钮,我可以解压缩设置目录中的所有文件,但是我希望该目录成为我在上面的列表框中放置的目录,而不是在代码中永久设置的目录。 / p>

        public static void MyMethod3()
        {
            string startPath = @"C:\testfolder\testprop\practicefolder\";
            string extractPath = @"C:\testfolder\testprop\practicefolder\unzippedstuff";
            Directory.GetFiles(startPath,"*.zip",SearchOption.AllDirectories).ToList()
                .ForEach(zipFilePath =>
                {
                    var extractPathForCurrentZip = Path.Combine(extractPath,Path.GetFileNameWithoutExtension(zipFilePath));
                    if (!Directory.Exists(extractPathForCurrentZip))
                    {
                        Directory.CreateDirectory(extractPathForCurrentZip);
                    }
                    ZipFile.ExtractToDirectory(zipFilePath,extractPathForCurrentZip);
                });
        }

我实际上想同时将同一路径传递给其他一些函数/方法/进程,但这似乎是最干净的示例。

很抱歉,如果这是一个愚蠢/简单的问题,或者我做的很多事情都非常错误。我尝试了很多事情,看起来很可行,但是没有成功。

解决方法

创建一个字段并将其用作变量,以便整个类都可以使用

,

我最终遵循以下答案:How to make a variable available to all classes in XNA/monogame?

“只需​​创建一个静态类,您将在其中存储所有全局变量,并且可以从所有类中访问它。”

    public static class MyGlobals
    {
        public static string finalPathForWork { get; set; }
    }

我敢肯定这不是最好的方法,但它目前已经奏效了。