在C#中处理文件资源管理器如何更改为“所有文件”选项

问题描述

我正在尝试使用C#处理文件资源管理器,但是我不知道如何选择“所有文件”选项

enter image description here

我已经成功在文件名文本框中输入了文件路径,并且可以按“确定”按钮。但是如果我无法按“所有文件”进行过滤,则无法选择文件

System.Windows.Forms.SendKeys.SendWait(@"C:\Users\email\Desktop\Hardware Hub\images\" + ID + ".png");
System.Windows.Forms.SendKeys.SendWait("{ENTER}");

解决方法

您不必使用SendKeys。您可以使用FileName属性填充输入字段,并使用FilterIndex属性在OpenFileDialog实例上选择“所有文件”。

var fileContent = string.Empty;
var filePath = string.Empty;

using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
    openFileDialog.InitialDirectory = "c:\\";
    openFileDialog.FileName = "Your filename"; // Sets the file name input
    openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    openFileDialog.FilterIndex = 2; // Sets filter to 'All Files'
    openFileDialog.RestoreDirectory = true;

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        //Get the path of specified file
        filePath = openFileDialog.FileName;

        //Read the contents of the file into a stream
        var fileStream = openFileDialog.OpenFile();

        using (StreamReader reader = new StreamReader(fileStream))
        {
            fileContent = reader.ReadToEnd();
        }
    }
}

MessageBox.Show(fileContent,"File Content at path: " + filePath,MessageBoxButtons.OK);