SoFunction
Updated on 2025-03-07

C# determines the suffix of file path

C# determines whether the suffix of the file path is a certain suffix. By parsing the file name and checking its extension, it determines whether the suffix of the file is .dcm.

Taking .dcm as an example, the code is as follows:

Direct judgment:

using System;  
using ;  
  
class Program  
{  
    static void Main()  
    {  
        string fileName = "";  
        string extension = (fileName);  
          
        if (extension == ".dcm")  
        {  
            ("The file name ends with .dcm.");  
        }  
        else  
        {  
            ("The file name does not end with .dcm.");  
        }  
    }  
}

Or use method:

using ;

public bool IsFileExtensionDcm(string filePath)
{
    // Get the full path to the file    string fileFullPath = filePath;

    // Use to get filename without extension    string fileNameWithoutExt = (fileFullPath);

    // Use to get file extensions (including dots)    string fileExtension = (fileFullPath);

    // Check whether the extension is consistent with ".dcm" (ignoring upper and lower case)    return (".dcm", );
}

// How to usestring filePath = @"C:\path\to\your_file.dcm";
if (IsFileExtensionDcm(filePath))
{
    ("The file's suffix is ​​.dcm");
}
else
{
    ("The file's suffix is ​​not.dcm");
}

Or save the string suffix name in a dictionary or array, and judge by comparing the obtained actual suffix name with the content in the list:

public static class FileExtensionChecker
{
    private static readonly HashSet<string> ImageExtensions = new HashSet<string>
    {
        ".dcm", 
        ".jpg", 
        ".jpeg", 
        ".png",
        // Other image extensions...    };

    public static bool IsImageFile(string filePath)
    {
        string fileExtension = (filePath).ToLowerInvariant();
        return (fileExtension);
    }

    public static bool HasExtension(string filePath, string extension)
    {
        string fileExtension = (filePath).ToLowerInvariant();
        return fileExtension == ();
    }
}

// How to usestring filePath = @"C:\path\to\your_file.dcm";

if ((filePath))
{
    ("This is an image file");
}

if ((filePath, ".dcm"))
{
    ("The file is in .dcm format");
}

The aboveIsImageFileThe method uses a collection (HashSet) to store and quickly query the commonly used extensions of image files, andHasExtensionThe method can directly accept a string parameter to check the specific suffix name.

This is the article about C# judging the suffix of file paths. For more related contents of C# file path suffix, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!