Search code examples
c#winformsif-statementfile-extension

C# Path.GetExtension 'If' Statement


My previous question was closed due to the fact that there are supposedly tied to Path.GetExtension.

Apparently, you may be able to get a file extension by Open Dialog using this function, however, may I know how to use Path.GetExtension in 'If' Statements/ 'If Statement'-like functions?

// SAMPLE CODE 1
OpenFileDialog1.Filter = "Image Files (JPG,PNG,GIF)|*.JPG;*.PNG;*.GIF";


// SAMPLE CODE 2
if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
   string ext = Path.GetExtension(OpenFileDialog1.FileName); 



// SAMPLE CODE 3
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);
    }
}

So in this case, how can this code be organized as to create if statements for different file extensions?


Solution

  • I think you want this:

    if(DialogResult.OK == saveDialog.ShowDialog())
    {
        var extension = Path.GetExtension(saveDialog.FileName).ToLower();
        if (extension.Equals(".jpg"))
        {
    
        }
        else if (extension.Equals(".png"))
        {
    
        }
        else
        {      
           throw new ArgumentOutOfRangeException(extension);
        }
    }
    

    if this dos not help you please add more detail