Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何仅打开.dat文件。在C中#_C#_Winforms - Fatal编程技术网

C# 如何仅打开.dat文件。在C中#

C# 如何仅打开.dat文件。在C中#,c#,winforms,C#,Winforms,我试图打开一个文件,但我希望它只过滤到.dat文件 using (OpenFileDialog fileChooser = new OpenFileDialog()) { result = fileChooser.ShowDialog(); fileName = fileChooser.FileName; //Get file name. fileChooser.Filter = "Data File|*.dat;"; fileChooser.DefaultExt

我试图打开一个文件,但我希望它只过滤到.dat文件

using (OpenFileDialog fileChooser = new OpenFileDialog())
{
    result = fileChooser.ShowDialog();
    fileName = fileChooser.FileName; //Get file name.
    fileChooser.Filter = "Data File|*.dat;";
    fileChooser.DefaultExt = "dat";
    fileChooser.AddExtension = true;
}

在“使用”筛选器中使用OpenFileDialog时,defaultExt和Addextension不起作用。

您应该在调用“ShowDialog”方法之前设置筛选器。

这应该起作用

using (var fileChooser = new OpenFileDialog())
{
    // define the filters (first description | first filter; second description ...
    fileChooser.Filter = "Data File|*.dat";
    // select the first filter
    fileChooser.FilterIndex = 1;
    fileChooser.DefaultExt = "dat";
    fileChooser.AddExtension = true;

    // show the Opendialog
    if (fileChooser.ShowDialog() == DialogResult.OK)
    {
        // get the path of specified file
        var filename = fileChooser.FileName;

        // use the filename to open the file...
    }
}

;“;
应该是
可能值得一读,以获得更全面的示例(如果您使用的是WPF)。如果您使用的是Winforms,请参阅下面的“我的链接”。ShowDialog()不应该是最后一个要调用的吗?
defaultExt和Addextension不起作用。
您复制的代码是用于(WPF)的。您可能正在使用Winforms()。