By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,668 Members | 1,704 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,668 IT Pros & Developers. It's quick & easy.

Creating file name form string

P: n/a
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 ?


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

lcRetVal = StrTran(lcRetVal, cSearchFor[i].ToString(),
return lcRetVal;
/// <summary>
/// Searches one string into another string and replaces all occurences
/// 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
//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();

Jun 28 '08 #1
Share this Question
Share on Google+
1 Reply

P: n/a
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

Jun 30 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.