简体   繁体   中英

Eliminate file extension with GetFileNameWithoutExtension

I used this method Path.GetFileNameWithoutExtension to eleminate file extension from string like from "abc:file.jpg" to "abc:file" but when i do this

Path.GetFileNameWithoutExtension("abc:file.jpg") 

it shows the result as "file". It also removed "abc:". Why has it happened ? Is there any better way to get this problem solved?

The char ":" (colon) is not legal as part of a filename. It interpret it as a path divider so it will remove it and anything before it when you request only the filename.

Here is one way you can check if the filename is valid:

This function will return true for valid filenames, and false for invalid ones:

private bool IsValidFilename(string filename)
{
    //
    //-- Get array with invalid chars for filenames
    //
    char[] illegalChars = Path.GetInvalidFileNameChars;
    //
    //-- Go through each char in filename and check if the char is
    //   in our array of invalid chars
    //
    foreach (char c in filename) {
        if (illegalChars.Contains(c))
            return false;
    }
    //
    //-- All are valid, return true
    //
    return true;

}

If the above function returns false you can use the next function to format the filename and remove the illegal chars (there exists os-functions to do this IIRC, but it's a simple exercise to do manually):

private string MakeFilenameValid(string filename, char replacment)
{
    //
    //-- Get array with invalid chars for filenames
    //
    char[] illegalChars = Path.GetInvalidFileNameChars;
    StringBuilder validFilename = new StringBuilder();
    //
    //-- Go through each char in filename and check if the char is
    //   in our array of invalid chars. If it is, replace it
    //
    foreach (char c in filename) {
        if (illegalChars.Contains(c)) {
            validFilename.Append(replacment);
        } else {
            validFilename.Append(c);
        }
    }
    //
    //-- Return filename
    //
    return validFilename.ToString;

}

Example of usage:

private void Button1_Click(System.Object sender, System.EventArgs e)
{
    string filename = "abc:file.jpg";

    if (!IsValidFilename(filename)) {
        filename = MakeFilenameValid(filename, "_");
    }

    MessageBox.Show(filename);

}

In VB:

Private Sub Button1_Click(sender As System.Object, _
                          e As System.EventArgs) Handles Button1.Click

    Dim filename As String = "abc:file.jpg"

    If Not IsValidFilename(filename) Then
        filename = MakeFilenameValid(filename, "_")
    End If

    MessageBox.Show(filename)

End Sub
Private Function IsValidFilename(filename As String) As Boolean
    '
    '-- Get array with invalid chars for filenames
    '
    Dim illegalChars() As Char = Path.GetInvalidFileNameChars
    '
    '-- Go through each char in filename and check if the char is
    '   in our array of invalid chars
    '
    For Each c As Char In filename
        If illegalChars.Contains(c) Then Return False
    Next
    '
    '-- All are valid, return true
    '
    Return True

End Function
Private Function MakeFilenameValid(filename As String, replacment As Char) As String
    '
    '-- Get array with invalid chars for filenames
    '
    Dim illegalChars() As Char = Path.GetInvalidFileNameChars
    Dim validFilename As New StringBuilder
    '
    '-- Go through each char in filename and check if the char is
    '   in our array of invalid chars. If it is, replace it
    '
    For Each c As Char In filename
        If illegalChars.Contains(c) Then
            validFilename.Append(replacment)
        Else
            validFilename.Append(c)
        End If
    Next
    '
    '-- Return filename
    '
    Return validFilename.ToString

End Function

It's better to name your files properly like abcfile.jpg or abc_file.jpg in the first place. then you'll be able to get complete file name.

试试这种方式..

Path.Combine(System.IO.Path.GetDirectoryName(path), System.IO.Path.GetFileNameWithoutExtension(path));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM