Question

my program has a save file option which is shown below :

        //Browse for file
        SaveFileDialog ofd = new SaveFileDialog();
        ofd.Filter = "CSV|*.csv";
        ofd.DefaultExt = ".csv";

        DialogResult result = ofd.ShowDialog();
        string converted = result.ToString();

        if (converted == "OK")
        {
            Master_Inventory_Export_savePath.Text = ofd.FileName;
        }

if I write the file name as "example" it saves correctly as a .csv however if I set the name as "example.txt" it saves as a text file , I've looked on msdn etc but even setting the default extension doesn't prevent this , any ideas on how to only allow files of .csv to be saved ?

Était-ce utile?

La solution

You could use the FileOk event to check what your user types and refuse the input if it types something that you don't like.

For example:

SaveFileDialog sdlg = new SaveFileDialog();
sdlg.FileOk += CheckIfFileHasCorrectExtension;
sdlg.Filter = "CSV Files (*.csv)|*.csv";
if(sdlg.ShowDialog() == DialogResult.OK)
    Console.WriteLine("Save file:" + sdlg.FileName);

 void CheckIfFileHasCorrectExtension(object sender, CancelEventArgs e)
 {
     SaveFileDialog sv = (sender as SaveFileDialog);
     if(Path.GetExtension(sv.FileName).ToLower() != ".csv")
     {
         e.Cancel = true;
         MessageBox.Show("Please omit the extension or use 'CSV'");
         return;
     }
 }

The main advantage of this approach is that your SaveFileDialog is not dismissed and you could check the input without reloading the SaveFileDialog if something is wrong.

BEWARE that the SaveFileDialog appends automatically your extension if it doesn't recognize the extension typed by your user. This means that if your user types somefile.doc then the SaveFileDialog doesn't append the .CSV extension because the .DOC extension is probably well known in the OS. But if your user types somefile.zxc then you receive as output (and also in the FileOk event) a FileName called somefile.zxc.csv

Autres conseils

can you not just force the .csv filetype by going like so in the last block of code?

if (converted == "OK")
{
    if (ofd.FileName.toString.EndsWith(".csv")<1)
    {
     Master_Inventory_Export_savePath.Text = ofd.FileName + ".csv";
    }
    else
    {
    Master_Inventory_Export_savePath.Text = ofd.FileName;
    }
}

Note - untested, but should give you a starting point....

Set the property AddExtension to true.

ofd.AddExtension = true;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top