Save File Dialog , restrict name

﹥>﹥吖頭↗ 提交于 2020-01-02 07:28:29

问题


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 ?


回答1:


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




回答2:


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




回答3:


Set the property AddExtension to true.

ofd.AddExtension = true;


来源:https://stackoverflow.com/questions/18743750/save-file-dialog-restrict-name

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