如何使用所选文件夹的变量?

时间:2017-10-22 03:14:41

标签: c# asp.net winforms

当我手动选择文件夹时,通过FolderBrowserDialog,我需要将路径替换为下面的代码。

其中"%ProgramFiles(x86)%\ MyApp"必须用所选文件夹+文件名的变量替换。

因此,在选择文件夹时,文件大小" testFile.txt" in" label1"应该显示(将有两个或更多这样的文件)。

    private void button1_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
        DialogResult result = folderBrowser.ShowDialog();
        if (result == DialogResult.OK)
        {
            // Determine the size of the file in KB (dividing the number of bytes by 1024)
            FileInfo fs1 = new FileInfo(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%\\MyApp\\testFile.txt"));
            long FileSize1 = fs1.Length / 1024;
            label1.Text = "testFile.txt (" + Convert.ToString(FileSize1) + " KB)";
            if (FileSize1 > 180 & FileSize1 < 186) // If the file is larger and smaller than the specified sizes
            {
                label1.ForeColor = Color.Green;
            }
            else
            {
                label1.ForeColor = Color.Red;
            }
        }
    }

决定,编辑:

            FileInfo fs1 = new FileInfo(folderBrowser.SelectedPath + "\\testFile.txt");

            FileInfo fs1 = new FileInfo(Path.Combine(folderBrowser.SelectedPath, "testFile.txt"));

1 个答案:

答案 0 :(得分:1)

官方文档中有专门针对此项目的项目:How to: Choose Folders with the Windows Forms FolderBrowserDialog Component

  

使用FolderBrowserDialog组件选择文件夹

     
      
  1. 在一个过程中,检查FolderBrowserDialog组件的DialogResult属性,以查看对话框是如何关闭的并获取   FolderBrowserDialog组件的SelectedPath属性的值。
  2.   
  3. 如果您需要设置将出现在对话框树视图中的最顶层文件夹,请设置RootFolder属性,   Environment.SpecialFolder枚举的成员。
  4.   
  5. 此外,您可以设置Description属性,该属性指定显示在顶部的文本字符串   文件夹浏览器树视图。
  6.         

    在下面的示例中,使用FolderBrowserDialog组件   选择一个文件夹,类似于在Visual Studio中创建项目时   并提示您选择要保存的文件夹。在此示例中,   然后,文件夹名称显示在窗体上的TextBox控件中。它   将位置放在可编辑区域中是个好主意,例如a   TextBox控件,以便用户可以编辑自己的选择   错误或其他问题。此示例假定带有a的表单   FolderBrowserDialog组件和TextBox控件。

    public void ChooseFolder()
    {
        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
        {
            textBox1.Text = folderBrowserDialog1.SelectedPath;
        }
    }
    

根据该示例,您可以使用folderBrowser.SelectedPath获取所选文件夹的字符串。