简体   繁体   English

如何只打开 a.dat 文件。 在 C#

[英]How to open only a .dat file. In C#

I'm trying to open a file but I want it filter out to only.dat file.我正在尝试打开一个文件,但我希望它过滤到 only.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;
}

When having a OpenFileDialog in "using" the filter, defaultExt and Addextension doesn't work.在“使用”过滤器中使用 OpenFileDialog 时,defaultExt 和 Addextension 不起作用。

You should set filters before the call of "ShowDialog" method.您应该在调用“ShowDialog”方法之前设置过滤器。

This should work.这应该有效。

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...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM