【问题标题】:Get one String from a Method into another Method从一个方法中获取一个字符串到另一个方法中
【发布时间】:2016-10-07 21:32:05
【问题描述】:

我目前正在编写一个程序,我对这个主题很陌生。 我从一个程序开始,您可以在其中选择一个 zip 文件并将其解压缩。

对于这两件事(选择、解压缩),我都使用了一个按钮。所以有一个选择按钮和一个解压缩按钮。

现在选择文件后我想把目录变成一个字符串,这样解压方法就可以解压了。

但是我不知道如何把这个目录变成一个字符串。 我试过了 string fileDir = fdlg.FileName 但是这个字符串在 unzip 方法中不起作用。

我该如何解决这个问题?

选择代码:

private void button2_Click(object sender, EventArgs e)
{
    OpenFileDialog fdlg = new OpenFileDialog();
    fdlg.Title = "Test - Selec ZIP File";
    fdlg.InitialDirectory = @"c:";
    fdlg.Filter = "Only ZIP Files|*.zip";
    fdlg.FilterIndex = 2;
    fdlg.RestoreDirectory = true;
    if (fdlg.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = fdlg.FileName;
    }
}

【问题讨论】:

  • fdlg 仅限于按钮单击事件处理程序,因此您无法从其他事件处理程序访问它。您将文件名存储在 textBox1.Text 中,因此您可能应该将其从其他事件处理程序中提取出来。

标签: c# visual-studio openfiledialog


【解决方案1】:

一种可能性是在类级别而不是在事件内部声明string 变量:

string fileDir = "";

private void button2_Click(object sender, EventArgs e)
{
    OpenFileDialog fdlg = new OpenFileDialog();
    fdlg.Title = "Test - Selec ZIP File";
    fdlg.InitialDirectory = @"c:";
    fdlg.Filter = "Only ZIP Files|*.zip";
    fdlg.FilterIndex = 2;
    fdlg.RestoreDirectory = true;
    if (fdlg.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = fdlg.FileName;

        //copy here the filename
        fileDir = fdlg.FileName;
    }
}

现在您应该可以在整个班级中使用fileDir

【讨论】:

  • 谢谢。这解决了我的问题^^
【解决方案2】:

在文本框中显示路径时,同时可以将路径存储在字符串中

textBox1.Text = fdlg.FileName;
string path=textBox1.Text;

【讨论】:

    猜你喜欢
    • 2013-05-05
    • 1970-01-01
    • 2015-03-13
    • 2011-03-21
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多