Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file extension from Save file dialog?

Tags:

c#

I would like to be able to save image according to extension that is entered in the save file dialog. I have found out that simply entering e.g. "JPG" does not cause the Save method to use this format of course. Parsing the extension and then using e.g. switch and setting correct format sounds a bit ackward to me. Or there is no better way?

like image 453
Mocco Avatar asked Feb 14 '11 10:02

Mocco


People also ask

How do I save a .file extension?

Click the File menu and click Save as. 3. In the File name text box, type "filename. extension" and click Save.

What displays a file dialog for saving a file?

To save a file using the SaveFileDialog component. Display the Save File dialog box and call a method to save the file selected by the user. Use the SaveFileDialog component's OpenFile method to save the file. This method gives you a Stream object you can write to.

What is .save extension?

what is a . save file? Files with the . save extension are temporary files containing data associated with text documents created using the Unix Nano text editing application. These SAVE files are created when this text editing application has limited memory resources at its disposal.

What is the extension of C# file?

Files with . cs extension are source code files for C# programming language.


1 Answers

you can get the file name specified in the SaveDialog.FileName then with Path.GetExtension() or similar you can get the string which will be used as extension.

What you will do after depends on your specific application design, if you are saving a text file you can also call it image1.png, but it will still be a text file.

if you have an image object in memory and want to save in the proper format depending on the selected extension, I would use a switch/case and use the proper overload or parameter values of the Image.Save to handle the different image formats.

Example

if(DialogResult.OK == saveDialog.ShowDialog())
{
    var extension = Path.GetExtension(saveDialog.FileName);

    switch(extension.ToLower())
    {
        case ".jpg":
            // ToDo: Save as JPEG
            break;
        case ".png":
            // ToDo: Save as PNG
            break;
        default:
            throw new ArgumentOutOfRangeException(extension);
    }
}
like image 160
Davide Piras Avatar answered Oct 26 '22 13:10

Davide Piras