How does the AddExtension property work in C# 2.0?

江枫思渺然 提交于 2019-12-23 07:57:49

问题


I want to open a save file dialog, have the user enter a filename, and if they forget the .csv extension, have it tacked on.

It would seem that the SaveFileDialog AddExtension property would work, but its doesn't. I've even set the DefaultExt property to .csv, and still nothing gets tacked on. My file gets saved just fine, but sans extension, so the user can't just double click on the file and have it open in Excel.

I have to be missing something obvious. Here's what I've got

        SaveFileDialog sfd = new SaveFileDialog();
        sfd.DefaultExt = "*.csv";
        sfd.Filter = "Comma Separated(*.csv)|*.*";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            // Do my file saving
        }

回答1:


Try just using "csv" for the DefaultExt - also, you should be using this (it is IDisposable):

        using (SaveFileDialog sfd = new SaveFileDialog())
        {
            sfd.AddExtension = true;
            sfd.DefaultExt = "csv";
            sfd.Filter = "Comma Separated(*.csv)|*.*";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                // Do my file saving
            }
        }



回答2:


It doesn't tack on the extension in the dialog box, although it should. Instead, it tacks on the extension to sfd.filename when the dialog closes.



来源:https://stackoverflow.com/questions/389070/how-does-the-addextension-property-work-in-c-sharp-2-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!