human
human

Reputation: 755

SaveFileDialog doesn't show any possible extensions despite using Filter option

I'm creating right now an application in C# which saves data to the file upon clicking a button. The name and locations of the file is defined by the user, and i want the program to automatically add .txt extension to the name, as well as show only 1 possible extensions in "save files as" combobox. I have this code:

SaveFileDialog Dialog1 = new SaveFileDialog();
Dialog1.DefaultExt = "txt";
Dialog1.Filter = "Pliki tekstowe | *.txt";
Dialog1.AddExtension = true;

private void button1_Click(object sender, EventArgs e)
{
    if (Dialog1.ShowDialog() == DialogResult.OK)
    {
        System.IO.Stream fileStream = Dialog1.OpenFile();
        System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream);
        sw.WriteLine("Writing some text in the file.");
        sw.WriteLine("Some other line.");
        sw.Flush();
        sw.Close();
    }
    this.Close();
}

But whenever i click the button, i have no options to choose from in the combobox, as well as the .txt extensions are not added to the file name in case the extensions is not specified by the user himself. I know i can somehow bypass that by checking if the user gave the proper extensions, and in case he didn't add ".txt" to the name but i really wanted to know, why that piecei of code doesn't function. Any help?

Upvotes: 3

Views: 1644

Answers (3)

Fahad
Fahad

Reputation: 41

I had a similar issue where the save dialog box on firefox and safari doesn't detect the file extension even though I had Content-Type header set to "application/pdf". The issue turned out to be spaces in the name of the file. I replaced the file name with '-' (hyphens) and that fixed it.

Upvotes: 0

Ahmed ilyas
Ahmed ilyas

Reputation: 5822

take a look at the following example and see the difference:

http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog(v=vs.110).aspx

you should try firstly to add this to your filter:

"txt files (*.txt)|*.txt|All files (*.*)|*.*"  

for completeness you should add the (*.txt) string in your filter for descriptive reasons (thanks for clarifying Yuck). Try it - see what happens :) remember it is sensitive in terms of the string. so try not to put things like a space between the file extensions

Upvotes: 2

Yuck
Yuck

Reputation: 50835

The problem is the space. Just change it to this:

Dialog1.Filter = "Pliki tekstowe|*.txt";

and you should be in business.

Otherwise it's trying to match files of the pattern  *.txt (subtly compared to *.txt) - which you probably don't have.

Upvotes: 4

Related Questions