[Mono-list] Creating file name from string

Andrus kobruleht2 at hot.ee
Sat Jun 28 14:40:10 EDT 2008


I need to create legal file name form any string so that PDF and other
viewers show nice title.

This code should create legal file name in every platform supported by MONO
and .NET

I created method LegalFileName() for this which uses 2 helper methods.
It replaces <>\/:?*"| characters in name.

Is this best solution ?
Will LegalFineName return legal file name for every OS ?


Andrus.

    /// <summary>
    /// Creates valid file name for current OS
    /// </summary>
    /// <returns>Legal file name</returns>
    public static string LegalFileName(string proposedFileName)
    {
       return ChrTran(proposedFileName, "<>\\/:?*\"|", "[]      ").Trim();
    }

    /// <summary>
    /// Replaces each character in a character expression that matches a
character
    /// in a second character expression with the corresponding character in
a
    /// third character expression
    /// </summary>
    /// <example>
    /// Console.WriteLine(ChrTran("ABCDEF", "ACE", "XYZ"));  //Displays
XBYDZF
    /// Console.WriteLine(ChrTran("ABCD", "ABC", "YZ")); //Displays YZD
    /// Console.WriteLine(ChrTran("ABCDEF", "ACE", "XYZQRST")); //Displays
XBYDZF
    /// </example>
    /// <param name="cSearchIn"> </param>
    /// <param name="cSearchFor"> </param>
    /// <param name="cReplaceWith"> </param>
    public static string ChrTran(string cSearchIn, string cSearchFor, string
cReplaceWith)
    {
        string lcRetVal = cSearchIn;
        string cReplaceChar;
        for (int i = 0; i < cSearchFor.Length; i++)
        {
            if (cReplaceWith.Length <= i)
                cReplaceChar = "";
            else
                cReplaceChar = cReplaceWith[i].ToString();

            lcRetVal = StrTran(lcRetVal, cSearchFor[i].ToString(),
cReplaceChar);
        }
        return lcRetVal;
    }


    /// <summary>
    /// Searches one string into another string and replaces all occurences
with
    /// a third string.
    /// <pre>
    /// Example:
    /// StrTran("Joe Doe", "o", "ak");  //returns "Jake Dake"
    /// </pre>
    /// </summary>
    /// <param name="cSearchIn"> </param>
    /// <param name="cSearchFor"> </param>
    /// <param name="cReplaceWith"> </param>
    public static string StrTran(string cSearchIn, string cSearchFor, string
cReplaceWith)
    {
        //Create the StringBuilder
        StringBuilder sb = new StringBuilder(cSearchIn);

        //There is a bug in the replace method of the StringBuilder
        sb.Replace(cSearchFor, cReplaceWith);

        //Call the Replace() method of the StringBuilder and specify the
string to replace with
        return sb.Replace(cSearchFor, cReplaceWith).ToString();
    }



More information about the Mono-list mailing list