如何解决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; }
}
我敢肯定这不是最好的方法,但它目前已经奏效了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。