Creating file name form string

A

Andrus

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

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

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.ToString();

lcRetVal = StrTran(lcRetVal, cSearchFor.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();
}
 
C

cfps.Christian

That should work, you can also do the wrong thing by putting a try/
catch block around the creation to catch any errors and bubble it back
up.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top